Structure and Union in C
Hello Everyone, I want to know how many data types are storing in structure and union in c programming. I am working on c language know and I am a beginner, So I don't know much better knowledge in C. I know about union used for storing one of many data types that are available but I am a little bit confused in structure or suggest me head to head comparison between structure and union.
Try these:
https://en.cppreference.com/w/c/language/struct
https://en.cppreference.com/w/c/language/union
It's reference documentation, so maybe not the most friendly, but it's an excellent site that helped me a lot.
I'd say structs are more type-save. But unions are quite handy when you have different versions of savegame formats (backward compatibilty) and just extend the previous version a bit.
You should be mostly using structures. Unions are a powerful but special case tool.
Structures are a group of variables. They give you a way to use one name to refer to a collection of variables. Each variable get it's own space in memory. All the variables are packed one after another in memory.
So for example:
struct Vec2
{
float x;
float y;
};
Gets a you a block of memory containing space for TWO unique floating point numbers, one for x, one for y.
A union is a group of names that point to the same block of memory. They provide you with a way to access the same memory with different names. This is sometimes useful.
For example:
union Vec1
{
float x;
float y;
};
Gets you a block of memory with space for ONE floating point number. You can refer to the number by either x or y, but it is the SAME memory location and therefore the SAME number.
If you are asking 'why would I ever want to do that?', you're asking the right question! :)
Unions are useful in a handful of case but generally you're going to be using structures to store your data. My advice is to use structures and then one day you'll find yourself thinking 'what I really want to do is access this variable as either two ints or an array of 8 chars'. When that moment happens, you'll have found your use for unions.
https://withthelove.itch.io/