I have difficulty in understanding the use of union
in C. I have read lot of posts here on SO about the subject. But none of them explains about why union
is preferred when same thing can be achieved using a struct.
Quoting from K&R
As an example such as might be found in a compiler symbol table manager, suppose that a constant may be an int, a float, or a character pointer. The value of a particular constant must be stored in a variable of the proper type, yet it is most convenient for table management if the value occupies the same amount of storage and is stored in the same place regardless of its type. This is the purpose of a union a single variable that can legitimately hold any of one of several types. The syntax is based on structures:
union u_tag {
int ival;
float fval;
char *sval;
} u;
The usage will be
if (utype == INT)
printf("%d\n", u.ival);
if (utype == FLOAT)
printf("%f\n", u.fval);
if (utype == STRING)
printf("%s\n", u.sval);
else
printf("bad type %d in utype\n", utype);
The same thing can be implemented using a struct. Something like,
struct u_tag {
utype_t utype;
int ival;
float fval;
char *sval;
} u;
if (u.utype == INT)
printf("%d\n", u.ival);
if (u.utype == FLOAT)
printf("%f\n", u.fval);
if (u.utype == STRING)
printf("%s\n", u.sval);
else
printf("bad type %d in utype\n", utype);
Isn't this the same? What advantage union
gives?
Any thoughts?