Size of union will be the size of the biggest variable.
Why do we need Union in the first place?
Sometimes we may not need the data of all the (related) data items of a complex data structure and be storing/accessing only one data item at a time. Union helps in such scenarios.
e.g.,
typedef union
{
int Wind_Chill;
char Heat_Index;
} Condition;
typedef struct
{
float temp;
Condition feels_like;
} Temperature;
Wind Chill is only calculated when it is cold and heat index is used only when it is hot. There is no need for both of them at the same time. So when we specify the temp, feels_like will have only one value - either wind chill or heat index, but not both.
The following simple program illustrate the above explanation:
% cat structunion.c
#include <stdio.h>
#include <stdlib.h>
typedef union
{
int Wind_Chill;
char Heat_Index;
} Condition;
typedef struct
{
float temp;
Condition feels_like;
} Temperature;
void main()
{
Temperature *tmp;
tmp = (Temperature *)malloc(sizeof(Temperature));
printf("\nAddress of Temperature = %u", tmp);
printf("\nAddress of temp = %u, feels_like = %u", &(*tmp).temp, &(*tmp).feels_like);
printf("\nWind_Chill = %u, Heat_Index= %u\n", &((*tmp).feels_like).Wind_Chill, &((*tmp).feels_like).Heat_Index);
}
% cc -o structunion structunion.c
% ./structunion
Address of Temperature = 165496
Address of temp = 165496, feels_like = 165500
Wind_Chill = 165500, Heat_Index= 165500
Great Content in your Blog... helps a lot refreshing some basic concepts... Thanks a lot....
ReplyDeleteThe explanation is easy to understand.
ReplyDeleteSimple but good explanation, thanks
ReplyDeletesimple,easy,good .
ReplyDeletethanks
Simple and beneficial. Thanks.
ReplyDeleteyes its too good to revise
ReplyDeleteyes its too good to revise
ReplyDeleteWonderful explanation, and great article!
ReplyDeleteI have bumped into this website after googling and was glad to find a detailed, comprehensible and yet easy to understand explanation. I think that the most important thing on this article is the example, that makes really clear why one should use the union anyhow. Thanks a lot!
thanks boss
ReplyDeleteThe Best Explanation. Thanks a lot dude!!
ReplyDeleteThanks for your detailed explanations! They really helped me understand! Thank you very much for your effort! Regards from Paul T.
ReplyDeleteKIS, GOOD
ReplyDelete