type conversion within a union

J

James Brown

All,

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 is simple enough to change my code to not require a union, this is more
of a curiosity right now..

thanks,
James
 
K

Keith Thompson

James Brown said:
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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,070
Latest member
BiogenixGummies

Latest Threads

Top