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


Example


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.

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.

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.

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.


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 Reply

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