← Previous Next →


Union:

Union is a user defined data type which can hold multiple variable(of different data type). It is very much similar to structure except use of internal memory.

For example: You want to store information for any person like - name, id, phone.

Syntax :

union variable-name 
{
    data-type1 var1;
    data-type2 var2;
    data-type3 var3;
};

Example :

union Person
{
   char name[30];
   int id; 
   int phone;
}; 

Difference between Structure and Union

struct Person1
{
    char name[30];
    int id;
    int phone;
};

union Person2
{
   char name[30];
   int id; 
   int phone;
}; 

struct Person1 p1 ;
union Person2 p2 ;

printf("size of struct-person : %d", sizeof(p1));
printf("size of struct-person : %d", sizeof(p1));

Output :

size of union-person : 30
size of struct-person : 38

If we calculate the size : 1*30 + 4*1 + 4*1 = 38 ( size of char = 1 byte, size of int = 4 byte)

So as you can see the difference union takes memory which is equal to it biggest size variable. From above example, name variable is taking 30 byte of memory which is size of union Person.

← Previous Next →