Let me explain you by an example.. struct test { int temp1; char temp2; } test_1; union test { int temp1; char temp2; } test_2; when you take the size of both then you will see the difference. in case of structure sizeof(test_1) = 5 (I am taking the integer size as 4 bytes) whereas in caes of union sizeof(test_2) = 4 In union the memory occupied by the largest data is being reused to store the other members of the union.In this case it happen to INT so the size came 4. Hope it will make things more clear
Just checkout if this is true sizeof(test_1) = 5 Because of packaging format it will be 8 ( assuming what you are assuming )
I agree...... And I appreciate ur immediate concern. Forgot the padding issue...Excatly the size will be 8 due to insertion of extra bytes by compiler. Thank you once again for correcting me and sorry for the mistake.
the amount of memory saved is so small to the extend that i would like to ask who cares about this few bytes ? seriously !!!
The obvious example of a use for unions is a spreadsheet where a cell can contain a date, number, some text, a formula or other things depending on the design. Another use of unions is to convert from one data type to another.
It can also be used where an application will be used where every byte used is important, like lets say if you are writting an application for a small calculator which has very less memory, now every byte here being used is very important! Hence, union will be prefered. There maybe other examples too like this one