Unions in C Language


Unions and structures are similar in concept. The syntax of unions in C programming language is also similar to that of structure. The difference between structures and unions is of the storage. In structure all the members have their own storage location but in unions all the members share a single memory and this memory storage is equal to the largest data member. The data members of union cannot be handled at same time.

The following is the syntax to declare a union by using union keyword:

union unit

{

 int m;

 float x;

 char c;

} u1;

 In the above example u1 is declared of type union unit. The data members of union are three and all of them are of different data types. But we can use only one item of the union at a time. This is because the data member of union is assigned only one location irrespective of its size.


Accessing a Union Member:

The following is the syntax to access a union member; it is similar to access the data member of a structure:

union testing

{

 int a;

 float b;

 char c;

} t1;

t1. a ;    // accessing the members of structure

t1. b ;

t1. c ;


Complete Example for Union:

Consider the following example in which we have used union:

CODE:

# include <stdio. h>

# include <conio. h>

union unit

{

 int x;

 float y;

 char ch;

};

int main ( )

{

 union unit u1;

 u1. x = 10;

 u1. y = 10.2;

 u1. ch = ‘c’;

 clrscr ();

 printf (“%d\n”, u1. x);

 printf (“%f\n”, u1. y);

 printf (“%c\n”, u1. ch);

 getch ();

 return 0;

}

OUTPUT:

2423.342

12421.324

c

In the above example it can be seen that the values printed for x and y are the wrong values and the value for the variables ‘ch’ is correct this is because the union will allocate the memory to currently saved variable.