About Lesson
A union is a variable that may hold objects of different types and sizes at different times, with the compiler keeping track of size and alignment requirements. They provide a way to manipulate different kinds of data in a single area of storage. For example:
union u_tag { int ival; float fval; char *sval; } u;
Here, the variable u will be large enough to hold the largest of the three type. Any one of these types may be assigned to u and then used in expressions. It is the programmer’s responsibility to keep track of which type is currently stored in a union.
Members of a union are accessed just like structure members using “.” and “->” operators. If we have a variable utype which keeps track of the current type stored in u, then we could print its value using the following code.
if (utype == INT) printf("%d\n", u.ival); else if (utype == FLOAT) printf("%f\n", u.fval); else if (utype == STRING) printf("%s\n", u.sval); else printf("Invalid type");