C Unions


  • Like structure union is also a collection of similar and dissimilar data types but difference is that it holds only one object at a time.
  • As we know in structure every data member has its own memory location but data members of unions have same memory address.
  • Union can contain one member at a time in a single area of storage.
  • Union can contain the members of different-different data type like int, float, char etc.
  • The size of union is equal to the size of the largest data member present in union.
  • Union takes less memory because it occupies the memory of largest member of union.
  • The basic syntax to declare a union is as follows:
  • union union_name

    {

    Datatype variable1;

    Datatype variable2;

    .................................

    .................................

    } [one or more union variables];

  • We can access the union member with the help of '.' (Dot operator) like structure.
  • Here is an example of Union:
Example
#include<stdio.h>

#include<conio.h>

union data

{

int data1;

float data2;

char data3;

};

void main()

{

union data d;

d.data1=2;

d.data2=3.4;

d.data3='H';

printf("Size of union:%d",sizeof(d));

printf("\ndata1=%d,data2=%f,data3=%c",d.data1,d.data2,d.data3);

getch();

}

The output of the above program is as follows:

Output
Size of union=4

data1=300123, data2= 323031, data3=H

In the above example union contains three variables int, float and char. As we know int , float and char occupies 4,4 and 1 byte respectively in the memory location that is why union contains size of largest data member that is 4. Here, we can see that values of data1 and data2 members of union are garbage values because final value assigned to the variable has occupied the memory location and this is the reason that the value of data member data 3 is getting printed very well.