union tag
{
int i;
float b;
char c;
}var;
Here the variable varis of type union tag. Here the union contains three data members of different types but we can use only one member at a time. This is due to the fact that only one location is provided to the union variable. Here the member float bwill take the maximum space (4 bytes), so the space provided for the union variable is 4 bytes. If the above declaration were a structure then the space required for the variable would have been 7 bytes.
Like structure members, we can access union members with statements like var.i, var.b, var.c. While accessing value from an union member, we should make sure that we are accessing the member in which the last value is assigned.
Difference between structure and union
In a structure in C programming language, each member has a storage location once it is associated with the structure. In a union, all the members use the same location. A union can contain members of different data types, but it can handle only one member at a time
The storage location allocated to a structure is the sum total of the storage location needed to store all the members of the structure. In a union, the storage size is equal to the size of the largest member of the union.
No comments:
Post a Comment