What are the advantages of using Unions?

aspguy's Avatar, Join Date: May 2005
Contributor
What are the advantages of using Unions?
0
shabbir's Avatar, Join Date: Jul 2004
Go4Expert Founder
Save memory
0
atul.sharma12's Avatar, Join Date: May 2008
Go4Expert Member
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
0
shabbir's Avatar, Join Date: Jul 2004
Go4Expert Founder
Just checkout if this is true

sizeof(test_1) = 5

Because of packaging format it will be 8 ( assuming what you are assuming )
0
atul.sharma12's Avatar, Join Date: May 2008
Go4Expert Member
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.
0
docesam's Avatar, Join Date: Apr 2009
Light Poster
the amount of memory saved is so small to the extend that i would like to ask who cares about this few bytes ?

seriously !!!

Last edited by shabbir; 12Sep2009 at 18:39.. Reason: Font Size
0
shabbir's Avatar, Join Date: Jul 2004
Go4Expert Founder
Quote:
Originally Posted by docesam View Post
the amount of memory saved is so small to the extend that i would like to ask who cares about this few bytes ?

seriously !!!
Bigger font does not speak more.
0
xpi0t0s's Avatar, Join Date: Aug 2004
Mentor
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.
0
mayjune's Avatar, Join Date: Jun 2009
Invasive contributor
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