I am learning K&R C. In chapter 6.8 it states:
A union may only be initialized with a value of the type of its first member; thus union
u
described above can only be initialized with an integer value.
... and defines a union u as follows:
union u_tag {
int ival;
float fval;
char *sval;
} u;
I do not know how to understand this. What does it mean, the initialization of u
must be as:
u.ival = 323;
clearly, that is not the case , because I can initilize u
as:
u.fval = 1.0;
or
u.sval = "hi";
What does Ritchie mean?
The posted code is performing assignment, not initialization. The author meant that the following is valid initialization as 323
is an int
and the first member of u_tag
is an int
:
union u_tag u = { 323 }; /* Initializes u.ival. */
The following would be invalid as it would be attempting to initialize an int
with a char[]
:
union u_tag u = { "hi" };
However, since C99 this is no longer the case. In C99, designators were introduced:
union u_tag u = { .sval = "hi" };
In C89, if you wanted to initialize a union
with a value intended for a member other than its first you could copy an existing union
. This would particularly useful if you wanted to declare the union
as const
. For example:
union u_tag make_u_tag_with_fval(const float a_fval)
{
union u_tag u;
u.fval = a_fval;
return u;
}
const union u_tag u_fval = make_u_tag_with_fval(1.0);
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