union in C programming (C union)

C union is a collection of different variables. It is also a user defined variable like structure in C. An union can have several members but only one member can contain value at a particular point of time. For this we can say that union is a user defined data type but the difference with structure is that the union shares the same memory location.

Here is the syntax of a union in C.

Syntax of C union

The syntax of C union is as like as structure. The syntax of C union is as follows;

// C union syntax
union person{
  char name[50];
  int idNo;
};

How to create a union variable?

We can create a union variable in two way in C language. As like as structure here we will see the declaration of a union variable in two way. Let’s have a look at the following two way of declaration of C union.

First way:

union student{
  char name[30];
  int roll;
};

int main(){
  union student s1, s2, *s3;
  return 0;
}

Second way:

union student{
  char name[30];
  int roll;
} s1, s2, *s3;

Accessing member of a union

We can use (.) operator to access the member of a union and (->) operator to access for pointer variable.

union student{
  char name[20];
  int roll;
} s1, *s2;

s1.roll = 30;
s2->roll = 31;
// or
(*s2).roll = 31

Difference between union and structure in C

Let’s have a look at the following program to understand difference between union and structure in C programming;

// What is the difference between union and structure
#include <stdio.h>

union employee_from_union{
  char name[40];
  int id;
  float salary;
} e1;

struct employee_from_struct{
  char name[40];
  int id;
  float salary;
} e2;

int main(){
   printf("Size of union is = %d bytes", sizeof(e1));
   printf("\nSize of structure is = %d bytes\n", sizeof(e2));
   return 0;
}

Output of this program

c union, union in c, difference between union and structure

Cause of difference between size of structure and union variable:

Here the size of structure,

e2 = size of char name[40] + size of int id + size of float salary;

= (40 + 4 + 4) bytes

= 48 bytes

Where the size of union,

e1 = size of char name[40]

= 40 bytes

This is because the size of union variable will always will be the size of its largest member as all members of a union share the same memory.

Previous pageNested structure in C

Next pageStructure examples