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:
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.
The following is the syntax to access a union member; it is similar to access the data member of a structure:
t1. a ; // accessing the members of structure
t1. b ;
t1. c ;
Consider the following example in which we have used union:
# include <stdio. h>
# include <conio. h>
int main ( )
union unit u1;
u1. x = 10;
u1. y = 10.2;
u1. ch = ‘c’;
printf (“%d\n”, u1. x);
printf (“%f\n”, u1. y);
printf (“%c\n”, u1. ch);
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.