Unions in C programming

In this tutorial, we will learn about ‘union in C’, its uses and how it is different from structures.

unions in C

A union is a variable that may hold  objects of different types and sizes.

The declaration of a union type is similar to the declaration of a struct type. Just replace the struct keyword with union.

Syntax of Union:

struct structure_name 
{
    data_type member1;
    data_type member2;
    .
    .
    data_type memeber;
};  // semicolon is must in ending line.

For example: Creating structure of a Student .

union Student{
   int roll;
   char name[40];
};

Here, variable roll and name are called members of the union Student.

We can also declare variable for student as :

struct Student{
   int roll;
   char name[40];
} s1, s2, *s3; //variables of type Student.

Or

struct Student{
   int roll;
   char name[40];
} std;

int main(){
    std s1;
}

Accessing Union Variable


Accessing union variable is similar to that of structure.  ( . ) member operator for union objects and the (  -> ) operator for pointers to union objects.

In above example, we can access variable roll as:

s1.roll

Likewise, if you want to access name for union variable s3:

(*s3).name
or
s3->name


Difference between structure and
union


Difference between between structure and union can be demonstared by example:

#include <stdio.h>
union unionStudent
{
   char name[32];
   int roll;
} uStd;

struct structStudent
{
   char name[32];
   int roll;
} sStd;

int main()
{
   printf("size of union = %d", sizeof(uStd));
   printf("\nsize of structure = %d", sizeof(sStd));
   return 0;
}

Output

size of union = 32
size of structure = 36

More memory is allocated to structures than union


a struct defines a group of related variables and provides storage for all of its members, a union provides storage for a single variable, which may be one of several types.

In above program structure allocates memory for each variable. But union allocates memory equal to size of its largest variable.