Unions have the same syntax as that of a structure since both of them are similar. However, there is a major difference between them in terms of memory allocation. A structure is allocated memory for all the members of the structure whereas a union is allocated memory only for largest member of the union. This implies that, although a union may contain many members of different types, it can handle only one member at a time. Like structure, a union can be declared using the union keyword as shown below:
union student s1,s2;
In the above code student is the name of the union. Also s1 and s2 are union variables. Memory is allocated only for name member of the union. So, the limitation on unions is: only one member can be used at a time. Unions can be used in all places where a structure is allowed.
Below is a C program to demonstrate a union:
union student s1;
s1.grade = 'A';
s1.marks = 98;
printf("Name is: %s \n",s1.name);
printf("Grade is: %c \n",s1.grade);
printf("Marks are: %d",s1.marks);
In the above program we will only get the correct value 98 for the member s1.marks as in a union only one value can b e used and stored at a time. We will get unexpected values for other members: name and grade.