"James Brown" <em***@viahomepage.comwrites:
I have the following structure definition:
struct S
{
union U
{
double fval;
int ival;
} u;
};
Let's say I declare one like so:
struct S s;
s.u.fval = 5.0;
And later do this:
s.u.ival = (int)s.u.fval;
And the converse:
s.u.ival = 23;
s.u.fval = (double)s.u.ival;
I am unsure if it is legal to perform this conversion over the top of
union fields that share the same storage space? Can anyone clarify?
[...]
It's perfectly valid. You're reading the value of one union member,
and then storing the (converted) value in another union member; the
two operations won't interfere with each other.
Things that invoke undefined behavior are (C99 6.5p2):
Between the previous and next sequence point an object shall have
its stored value modified at most once by the evaluation of an
expression. Furthermore, the prior value shall be read only to
determine the value to be stored.
but you're not doing that here.
However, I'd drop the casts, and let the conversions be done
implicitly. It's tempting to add a cast to emphasize that a
conversion is happening; the problem is that the compiler doesn't
check that you're using the correct type. If you change ival from int
to long, but forget to change the cast so you're still converting to
int before storing the value, your code could break. If you leave the
cast out, the implicit conversion will always be the right one.
--
Keith Thompson (The_Other_Keith)
ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <* <http://users.sdsc.edu/~kst>
"We must do something. This is something. Therefore, we must do this."
-- Antony Jay and Jonathan Lynn, "Yes Minister"