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?
In the example you posted, the size of union would be the size of float (assuming it is the largest one - as pointed out in the comments, it can vary in a 64 bit compiler), while the size of struct would be the sum of sizes of float, int, char* and the utype_t (and padding, if any).
The results on my compiler:
union u_tag {
int ival;
float fval;
char *sval;
};
struct s_tag {
int ival;
float fval;
char *sval;
};
int main()
{
printf("%d\n", sizeof(union u_tag)); //prints 4
printf("%d\n", sizeof(struct s_tag)); //prints 12
return 0;
}
Unions can be used when no more than one member need be accessed at a time. That way, you can save some memory instead of using a struct.
There's a neat "cheat" which may be possible with unions: writing one field and reading from another, to inspect bit patterns or interpret them differently.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With