In this tutorial, we will learn about ‘union in C’, its uses and how it is different from structures.
A union is a variable that may hold objects of different types and sizes.
The declaration of a union type is similar to the declaration of a struct type. Just replace the struct keyword with union.
Syntax of Union:
}; // semicolon is must in ending line.
For example: Creating structure of a Student .
Here, variable roll and name are called members of the union Student.
We can also declare variable for student as :
} s1, s2, *s3; //variables of type Student.
Accessing Union Variable
Accessing union variable is similar to that of structure. ( . ) member operator for union objects and the ( -> ) operator for pointers to union objects.
In above example, we can access variable roll as:
Likewise, if you want to access name for union variable s3:
Difference between structure and
Difference between between structure and union can be demonstared by example:
printf("size of union = %d", sizeof(uStd));
printf("\nsize of structure = %d", sizeof(sStd));
size of union = 32
size of structure = 36
More memory is allocated to structures than union
a struct defines a group of related variables and provides storage for all of its members, a union provides storage for a single variable, which may be one of several types.
In above program structure allocates memory for each variable. But union allocates memory equal to size of its largest variable.