Unions in C - Example with Explanation

What is union ?

A union is special data type provided in C programming language which contains multiple data members possibly of different data types grouped together under a single name. All members in union occupy the same memory area. The size of the memory area is the size of the largest data member in the union.

How to declare a union ?

Syntax of union in c

union union_tag
{
data_type member1;
data_type member2;
.
.
.
data_type memberN;
}[one or more union variables];
The union_tag is optional. each data member in the union is a normal variable definition like int num, float num or any other valid definition.

Example of unions in c

union data
{
int no_of_copies;
char month_of_release[10];
int edition;
}info;

Explanation

Out of the three data members in the union only one can be set at a time. It means we can use the union variable info to set only one out of three data members viz. no_of_copies, month_of_release, and edition.

Example

info.no_of_copies=10; // now the union variable info contains no of copies
strcpy(info.month_of_edition,"June");now it contains month of release, it does not contain no of copies anymore
info.edition=4;// now it contains edition and it does not contain month of release anymore
That is only one member of union variable can accessed and set at a time.