Utility of a Union

Get introduced to the utility of a union with the help of a real-life example.

Store employee data

We should use a union whenever there is a need to access the same locations in multiple ways. Let’s see this with the help of a simple scenario. Suppose we want to store the following information about employees in an organization:

To store employee information, we can have two solutions.

Solution 1: Using a structure

Because the given information is dissimilar, we can use a structure to gather this information. See the code given below!

C
#include<stdio.h>
// Declares structure
struct employee {
char n[20];
char grade[ 4 ] ;
int age ;
char hobby[ 10 ] ;
int creditCard ;
char vehicle[ 10 ] ;
int dist ;
};
int main() {
struct employee e ;
// Prints size of structure variable
printf ("%d", sizeof(e));
}

We will either use the fields hobby and creditCard or vehicle and dist. Therefore, the first solution is not optimal, since it leads to a waste of space. Since the employee is either highly-skilled (HSK) or semi-skilled (SSK), we would either end up using pink blocks or blue blocks, not both.

Solution 2: Create a union between the fields

We can avoid wasting space by creating a union between the fields hobby and creditCard or vehicle and dist. See the code given below!

C
#include<stdio.h>
// Structure and union declaration
struct info1 {
char hobby[ 10 ] ;
int creditCard ;
};
struct info2 {
char vehicle[ 10 ] ;
int dist ;
};
union info {
struct info1 a ;
struct info2 b ;
};
struct employee {
char n[20];
char grade[ 4 ] ;
int age ;
union info f ;
};
int main() {
// Structure variable declaration
struct employee e ;
// Prints size of structure variable
printf ("%d" , sizeof(e));
}

In the second solution, there is no waste of space, since pink blocks and blue blocks share memory locations. For this sharing to be possible, they should be put into a union as shown in the figure.