Union in C

The 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.

  1. struct abc  
  2. {  
  3.    int a;  
  4.    char b;   
  5. }   

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.

  1. union abc  
  2. {  
  3.    int a;  
  4. char b;   
  5. }var;  
  6. int main()  
  7. {  
  8.   var.a = 66;  
  9.   printf("\n a = %d", var.a);  
  10.   printf("\n b = %d", var.b);  
  11. }   

Let's understand through an example.

  1. #include <stdio.h>  
  2. union abc  
  3. {  
  4.     int a;  
  5.     char b;  
  6. };  
  7. int main()  
  8. {  
  9.     union abc *ptr; // pointer variable declaration  
  10.     union abc var;  
  11.     var.a= 90;  
  12.     ptr = &var;  
  13.     printf("The value of a is : %d", ptr->a);  
  14.     return 0;  
  15. }