What is a union in C Language?

  • The union is a user-defined data type that allows storing multiple types of data in a single unit. However, it doesn’t occupy the sum of the memory of all members. It holds the memory of the largest member only.
  • In union, we can access only one variable at a time as it allocates one common space for all the members of a union.

Syntax of union

  1. union union_name
  2. {
  3. Member_variable1;
  4. Member_variable2;
  5. .
  6. .
  7. Member_variable n;
  8. }[union variables];

 

Let’s see a simple example

  1. #include<stdio.h>
  2. union data
  3. {
  4.     int a;      //union members declaration.
  5.     float b;
  6.     char ch;
  7. };
  8. int main()
  9. {
  10.   union data d;       //union variable.
  11.   d.a=3;
  12.   d.b=5.6;
  13.   d.ch=‘a’;
  14.   printf(“value of a is %d”,d.a);
  15.   printf(“\n”);
  16.   printf(“value of b is %f”,d.b);
  17.   printf(“\n”);
  18.   printf(“value of ch is %c”,d.ch);
  19.   return 0;
  20. }

Output:

value of a is 1085485921
value of b is 5.600022
value of ch is a

In the above example, the value of a and b gets corrupted, and only variable ch shows the actual output. This is because all the members of a union share the common memory space. Hence, the variable ch whose value is currently updated.