Union in C Programming

In C programming language, union is a special user defined data type that allows to store different data types in the same memory location.

“union”  uses the same memory location for multiple-purpose.

 Or

In a union data type, single variable, i.e., same memory location, can be used to store multiple types of data.

In c programming union is similar to the structure but major difference is that it requires less memory than structure.

Apart from this difference, you can define a union with many variables, but only one member can contain  single value at any given time.

Defining a Union

We can define union with “union” keyword. “union” defines a new user defined data type with one or more than one member.

Syntax of union definition:

In the union’s definition at the end & before the final semicolon, you can specify one or more union variables but it is optional.

Example:

Above define a union type named book having three members i, f, and c.

In the above example variables of Book is book1 and book2.

These variables can store an integer, a floating-point number, or a string of characters.

During the union definition, memory occupied by a union variable will be large enough to hold the largest member of the union.

In the above example, user defined data type Book will occupy 30 bytes of memory space because this is the maximum space which can be occupied by a character string. 

Example: Write a program to store and print the following information such as name, roll number, class and section of the student using union.

OUTPUT

In the above example, we can see that the values of name, rollno, and Class of union got corrupted because the final value assigned to the variable has occupied the memory location and this is the reason that the value of Section is getting printed very well.

Note: In union, one variable can contain a single value at any given time which is the main purpose of having unions −

Correct Implementation of Above program

OUTPUT