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. Union can be defined using keyword “union” as shown below.

Union in C

Defining Union

Syntax

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

Example

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 Variables

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;

Variable can also be declared at time of defining the union by just writing the variable name in between closing braces and semicolon.

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;
printf("%d",s1.rollno);

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 can be initialized at the time of declaration of variables. But only first member can be initialized and all other members can be initialized later on by either assigning value or reading value from keyboard. Consider below example.

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.

Lets make one simple program to under the concept of union in C.

#include<stdio.h>

void main()
{
 union student
 {
  int rollno;
  float mark;
  char gender;
 }s1;

  s1.rollno=20;
 printf("Roll No:%d",s1.rollno);

  s1.mark=90.5;
 printf("nMark:%f",s1.mark);

  s1.gender='m';
 printf("nGender:%c",s1.gender);
}

Output

Union in C

Explanation
The above program is self explanatory, still if you are facing any problem then comment below.

This is all about union in C. If you find any mistake or something missing in above tutorial then please mention it in the comments.

Leave a Comment

Your email address will not be published. Required fields are marked *