Utility of a Union
Get introduced to the utility of a union with the help of a real-life example.
We'll cover the following...
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!
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!
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.