Union in c

Union is a user defined data type which contains variables of different data types. Or we can say that, union is collection of dissimilar type of elements or data. The concept of union is taken from structure so the syntax of union is same as structure.


name_of_union{ member 1; 
member 2;
 . . . . .
 member n;


union student{
 int rollno;
 float mark;
 char gender;

In structure each member get separate memory for storage while in union all the members share same storage location. As all the members share same storage so we can work on only one member at a time. The compiler allocates total memory equal to the member having largest size. In above example mark has largest size of 4 bytes so the total memory allocated for a variable of union student type will be 4 bytes. 

Declaring Union Variable

We can declare variable of union in the same way we do for structure. For example if we want to declare variables for above union then it can be done in following way.

union student s1,s2;

Accessing Union Members

We can access a union member by using dot operator (.). Remember that, access only that variable whose value is currently stored. Consider below example.

s1.rollno = 20;
s1.mark = 90.0;

The above code will give erroneous output. This is because we have most recently sored value in mark and we are accessing rollno. When value is assigned to a member then the value that was assigned to any other member before is lost.

Initializing Union

union student s1 = {25}; //valid 
union student s1 = {80.5};  //will give undesired or erroneous output

In above example the first statement is correct while second statement will give undesired output because we are initializing second member mark (float type) of union student.


void main()
union student {
int rollno;
float mark;
char gender;
printf("Roll No:%d",s1.rollno);


Roll No=30