todayitryto: explain the Union data type

Union is a special data type that looks a lot like a ‘struct’ but the variables inside will all be stored in the same location in memory.

take a look at this code snippet

ALSO I WILL ASSUME sizeof(int) == 4 bytes

union Data{
int a;
char b;

int main (void)
union Data d;

d.a = 10;
d.b = ‘A’;

printf( “d.a : %d\n”, d.a);
printf( “d.b : %c\n”, d.b);
printf( “Memory size occupied by the union : %d\n”, sizeof(d));

return 0;
when this compiles, it should show this:

d.a : (probably garbage, not sure)
d.b : A
Memory size occupied by the union : 4

The size of the union is == to the size of the largest variable (in terms of bytes) that is inside it
d.a doesn’t show the number 10 since it shares its address in memory with d.b.
d.b being the last one to get assigned a value, will overwrite whatever d.a put in memory.
You should be thinking “This won’t be printing garbage if I just used ONE VARIABLE AT A  TIME”
THAT is the main purpose of the union data type.
The best way (and what I think is the only way) to use union is to wrap them in a struct with an identifier.
The identifier will be used to tell you which variable is being used in the union at the moment. (please don’t forget to implement/give the identifier a value)
Besides saving memory, having one data type that can handle all the data types you need is pretty handy

Wikipedia (which just sources The C Programming Language Book by Brian Kernighan and Dennis Ritchie)
stackoverflow (im sorry)
and tutorialspoint (it’s best if you already have an idea of the topic you are looking for before using this site, just my opinion)


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s