In this article, you'll learn about unions in C programming. More specifically, how to create unions, access its members and learn the differences between unions and structures.
Unions are quite similar to structures in C. Like structures, unions are also derived types.
Defining a union is as easy as replacing the keyword struct with the keyword union.
How to create union variables?
Union variables can be created in similar manner as structure variables.
} car1, car2, *car3;
union car car1, car2, *car3;
In both cases, union variables car1, car2 and union pointer variable car3 of type union car is created.
Accessing members of a union
Again, the member of unions can be accessed in similar manner as structures.
In the above example, suppose you want to access price for union variable car1, it can be accessed as:
Likewise, if you want to access price for the union pointer variable car3, it can be accessed as:
Difference between union and structure
Though unions are similar to structure in so many ways, the difference between them is crucial to understand.
The primary difference can be demonstrated by this example:
//defining a union
printf("size of union = %d", sizeof(uJob));
printf("\nsize of structure = %d", sizeof(sJob));
size of union = 32
size of structure = 40
More memory is allocated to structures than union
As seen in the above example, there is a difference in memory allocation between union and structure.
The amount of memory required to store a structure variable is the sum of memory size of all members.
But, the memory required to store a union variable is the memory required for the largest element of an union.
Only one union member can be accessed at a time
In the case of structure, all of its members can be accessed at any time.
But, in the case of union, only one of its members can be accessed at a time and all other members will contain garbage values.