C++ Unions
Unions
Just like Structures, the union is a user-defined data type. They provide better memory management than structures. All the members in the unions share the same memory location.
The union is a data type that allows different data belonging to different data types to be stored in the same memory locations. One of the advantages of using a union over structures is that it provides an efficient way of reusing the memory location, as only one of its members can be accessed at a time. A union is used in the same way we declare and use a structure. The difference lies just in the way memory is allocated to their members.
Creating a Union element
We use the union keyword to define the union.
The syntax for defining a union is,
Here’s one example of how a union is defined and used in main as a user-defined data type.
Initialising and accessing union elements
Different from how we used to initialise a struct in one single statement, union elements are initialised one at a time.
And also, one can access only one union element at a time. Altering one union element disturbs the value stored in other union elements.
Output:
Note: We can only use 1 variable at a time otherwise the compiler will give us a garbage value and the compiler chooses the data type which has maximum memory for the allocation.