What is the difference between a structure and Union
Printable View
What is the difference between a structure and Union
well, the books will tell you that they are very similar i.e. how to declare them, how to access the variables even declaring them
e.g.
struct example{
char var1;
char var2;
};
union next_eg{
char var3;
char var4;
};
struct example test;
union next_eg test2;
test.var1 = 'a';
test.var2 = 'b';
test2.var3 = 'c';
test2.var4 = 'd';
however, struct test has the size of 2 char whereas union test2 has the size of 1 char only.
this is because a union will take the size of the largest variable.
hence, if there were a int declared in the union then the size of that union will be 2 bytes, since int is 2 bytes long and char is 1 byte long.
refer to above example.
this also means that for a struct, you can use the variables at any time. for the union you can only use 1 of them at any one time.
clear?
it appears that the benefit of using unions is that if you only use 1 variable at any time, then you will save space.
feedback is welcome.
>>however, struct test has the size of 2 char whereas union test2 has the size of 1 char only.
Not totally true as the struct or union may be padded or 'byte aligned'. You can never assume sizeof(STRUCT)==sum(sizeof(elements of STRUCT)).
>>hence, if there were a int declared in the union then the size of that union will be 2 bytes, since int is 2 bytes long and char is 1 byte long.
Again not totally true on all OS and systems. int's being 4 bytes, UNICODE strings 2bytes ect.
Uses of unions are limited in my experience.
One good use is to return from a function.
If the function generates an error it can return ONLY the error in int form (iErrorCode) or if it works it can return ONE whole filled structure.Code:typedef union
{
int iErrorCode;
RETURN_BMP BMPResultValues;// a structure
RETURN_JPG JPGResultValues;// a structure
RETURN_TIFF TIFFResultValues;// a structure
} UNION_EXAMPLE;
UNION_EXAMPLE My_Function(int iData, ect);
It allows a function to act differently depending on the data sent to it.
The variable filled remains the same allowing some more 'reusablility' (if that is a word).