Unions are conceptually similar to structure, that is a user-defined data type that holds data of different types(heterogeneous).
The difference between structure and unions is in terms of storage. In the case of structure, each member has its own storage location whereas in the case of unions all the elements share the same memory locations.
The size of the structure is the sum of the size of all the elements and the size of the union is the size of the largest element present in it.
Please refer to the structure in C for a better understanding of the below section.
Diag-1: Structure and union memory

This implies that although union may contain many members of different types, they can store value in only one so they can be accessed.
union Emp
{
char x;
float y;
};
union Emp emp; // Creating a variable of union type
emp.x = 'c';
or
emp.y = 6.7;
They are accessed in a very similar manner to that of the structure by creating objects or union variables.
There are certain scenarios where we only want to use one of the members at a time. So in that case, using a union is a wiser option rather than using a structure. This will save us memory.
Unions allow data members who are mutually exclusive to share the same memory. This is quite important when memory is scarcer, such as in embedded systems.
The IP version can either be IPv4 or IPv6, so unions can be used to save memory.
Example:
#include <stdio.h>
Relevant Posts:
- Structure in C
- Function in C
- Difference between structure and union
- Structure padding
- Array of structure
- Pointer to structure
Categories: C Language
Leave a Reply