Union: Definition, Declaration & Initialization in C

Union, is a collection of variables of different types, just like a structure, however a union can only store information in one field at one time. This means, a union can be viewed as a variable type that can contain many different variables as members (like a structure), but only actually holds one of them at a time (unlike a structure).

One can visualize union as a chunk of memory that is used to store variables of different types. So, once a new value is assigned to a field, the existing data is wiped over with the new data. This can save memory if you have a group of data where only one of the types is used at a time. Therefore, the size of a union is equal to the size of its largest data member. In other words, the C compiler allocates just enough space for the largest member. This is because only one member can be used at a time, so the size of the largest, is the most one will need. In contrast, the size of a structure is equal to the sum of sizes of its members because every member is allocated a unique memory chunk.

The syntax for defining a Union and declaring a variable of Union is same as that of Structure; except the keyword used is union.

union <union-name>
{
<data-type> <variable-name>;
.
.
<data-type> <array-name> [<size>];
.
.
union <other-union-name>;
.
.
};

It should be noted that a structure can have union as a data member and union can have a structure as a data member.

The following code snippet defines a union student

union student
{
int marks;
float percentage;
};

Indeed if it would have been a structure then the size of this structure would have been 6 bytes. However, as it is a union its size is 4 bytes (largest data member is float).

The following code snippet defines, declares and initializes a union student.

union student
{
int marks;
float percentage;
} std1, std2 = {10};
/* Only one assignment is needed */