What is union in C?

Union in c is user-defined data type that stores different type of elements.

At once only one member can occupy memory.

Thus the size of a union at any given time is equal to the size of its largest element.

Syntax

union [union tag]{
 member definition;
 member definition;
 ...
}[member variable(s)];

Example

union student{
 char name[30];
 int roll_number;
}s1;

In the above example, student is union type and it contains 2 members i.e. name and roll_number. The size of the union is its largest member therefore in the above example, the size of student datatype is 30 bytes.


Accessing union members

Union members can be accessed through .(dot) operator.

For pointers using arrow operator (->).

Example

// C program to illustrate union
#include<stdio.h>
#include<string.h>
union student{
   char name[30];
   int roll_number;
  }s1;
int main()
{
  strcpy(s1.name,"Ram");
  s1.roll_number=20;
  printf("Name of the student %s \n",s1.name);
  printf("Roll number is %d \n",s1.roll_number);
  return 0;
}  

Output

Sample example of union in c

Pointer to union

Pointer to union can be created just like pointer to other primitive datatypes.

Example

// C program to illustrate pointer to union
#include<stdio.h>
int main(){
  union unit{
     int m;
     int n;
  };
  union unit a={100};
  union unit* pointer=&a;
  printf("Value of m is %d \n",pointer->m);
  pointer->m=200;
  printf("Value of m is %d \n",pointer->m);
  return 0;
}

Output

Pointer to union

Applications of union

  • Hardware input/output access
  • Bitfield sharing
  • word sharing
  • Low level polymorphism

Checkout how to cast to union in GNU documentation.


Advantage and disadvantage of union

Advantages of union

  • Space efficiency: It takes less memory space as compared to the structure.
  • It allocates memory size to all its members to the size of its largest member.

Disadvantage of union

  • It allows to access only one of it’s member at a time.

People also ask for

What is the use of union in C?

C unions are used to save memory. The size of a union is its size of the largest element.

What is difference structure and union?

Structure is user defined data type with memory allocated to all members of a structure. In case of union memory is allocated to a member for which the value is assigned. You can read more diffrence here.

Which is better structure or union?

If you want memory to be allocated to all members then use structure. If you want to use same memory location for two or more data members then use union.

How is the size of union decided by compiler?

Size is considered according to the largest member of the union.