Unions in C

For Complete YouTube Video: Click Here

In this class, we will understand Unions in C.

We have already discussed the concepts of structures.

Table of Contents

Unions in C

A Union is like a Structure consists of one or more members of different types.

The only difference is compiler allocates memory size equal to the size of the ‘largest member.’

Example

The image below is an example of structure.

Unions in C Example 1
Unions in C Example 1

If we assume that int is 4 bytes of space and double is 8 bytes, the compiler will allocate 12.

The memory allocated for the above structure is as shown below.

Unions in C Visualization of Structure
Unions in C Visualization of Structure

Similarly, if we consider union as shown below.

Unions in C Example 2
Unions in C Example 2

Union is the keyword used to create a union.

The union variable is ‘u.’

The largest among the two members is double with 8 bytes; the compiler will create only 8 bytes of space.

Unions in C Visualization of Union
Visualization of Union

The members of the structure will share these 8 bytes of space among the members.

Example 2

To have a better understanding, we will consider the example shown below.

Unions in C Example 3
Example 3

In the above example, j is the union variable.

The first line of code 12.5 will get allocated to the memory.

The second line of code ten will get overwritten.

When we try to print salary, which is overwritten by ten, the output of the print statement will be the value equal to the binary value of ten in floating-point representation.

If we try to print workerNo ten will get published.