Explore
ProGrad Programs
Placement Prep
TCS Codevita
Webinars
About Us

Edit
Reply




Edit

Union in C

Published on 06 Mar 2020

Union is similar to a structure. In a structure, each member has its own storage location whereas in a union, all the members share the same memory location.


1) The compiler allocates memory large enough to hold the largest variable type in the union.


Declaration syntax:

union student
{
int sno;
char sname[20];
int total;
float avg;
};

Here, the member's name requires the largest number of memory bytes (20). Hence 20 bytes will be allocated for a union variable, of this type.


2) Only one member can be accessed at a time. (ie., the currently active member alone can be accessed).


union item
{
int m;
float x;
char c;
} i;

int main()
{
i.m=370;
i.x=189.57;
i.c='A';
printf("%c",i.c);
printf("%f%d",i.x,i.m);
i.x=50.75;
printf("%f",i.x);
}


Advantages: Union saves storage space.


Disadavantage: There is no way to know which member of the union is currently active, unless the user keep track of it.


If you have any feedback about this article and want to improve this, please write to enquiry@faceprep.in