Union in C Language
Categories: C language
Union can be defined as a user-defined data type which is a collection of different variables of different data types in the same memory location. The union can also be defined as many members, but only one member can contain a value at a particular point in time.
Union is a user-defined data type, but unlike structures, they share the same memory location.
Let's understand this through an example.
The above code is the user-defined structure that consists of two members, i.e., 'a' of type int and 'b' of type character. When we check the addresses of 'a' and 'b', we found that their addresses are different. Therefore, we conclude that the members in the structure do not share the same memory location.
When we define the union, then we found that union is defined in the same way as the structure is defined but the difference is that union keyword is used for defining the union data type, whereas the struct keyword is used for defining the structure. The union contains the data members, i.e., 'a' and 'b', when we check the addresses of both the variables then we found that both have the same addresses. It means that the union members share the same memory location.
Let's have a look at the pictorial representation of the memory allocation.
The below figure shows the pictorial representation of the structure. The structure has two members; i.e., one is of integer type, and the another one is of character type. Since 1 block is equal to 1 byte; therefore, 'a' variable will be allocated 4 blocks of memory while 'b' variable will be allocated 1 block of memory.
The below figure shows the pictorial representation of union members. Both the variables are sharing the same memory location and having the same initial address.
In union, members will share the memory location. If we try to make changes in any of the member then it will be reflected to the other member as well. Let's understand this concept through an example.
var.a = 66;
printf("\n a = %d", var.a);
printf("\n b = %d", var.b);
In the above code, union has two members, i.e., 'a' and 'b'. The 'var' is a variable of union abc type. In the main() method, we assign the 66 to 'a' variable, so var.a will print 66 on the screen. Since both 'a' and 'b' share the memory location, var.b will print 'B' (ascii code of 66).