+ 1
What are the real cases where we should use union instead of structure or nested in structure??
I mean to say.....where should we use union in real life where we can access a lot of things by using structure !!
1 Resposta
+ 2
I think it is used for space optimization purpose when two parts of a data type are never used in the same time
For example:
typedef struct{
int key;
int mouseX;
int mouseY;
} EventInfos;
In this structure, a mouse click does not happen in the same event as a key pressed so it could be rewritten this way:
struct{
int eventType;
union{
int key;
int coords[2];
} data;
};
In this union, it does not change the size but if we add other events (mouse wheel, ...), the union will not grow much (depending on the data you add) but the structure would grow a lot (the first one)