Re: Address of a union member
- From: Tim Rentsch <txr@xxxxxxxxxxxxxxxxxx>
- Date: Tue, 29 Sep 2009 00:47:41 -0700
raltbos@xxxxxxxxx (Richard Bos) writes:
Keith Thompson <kst-u@xxxxxxx> wrote:
Consider, for example:
union foo bar;
int *p = &bar.i;
*p = 10;
bar.d = 12.34;
printf("*p = %d\n", *p);
The optimizer might assume that, since you just stored the value 10 in
*p, the value 10 must still be there, and optimize the printf to
something like puts("p = 10").
(The standard has more to say about whether this behavior is defined
or undefined and whether an optimizer is allowed to make this
assumption; I don't have my copy of the standard handy right now and
I'm too lazy to look it up.)
You're reading a member of a union which is not the last member that has
been assigned to. You're reading it indirectly, but you're still reading
it. This means that its bytes have unspecified values,
Probably you are misremembering. It's only bytes /other than/
the bytes of the member last stored that take unspecified
values. Bytes that overlap the member last stored take on
the values that were stored as a result of assigning to
that member.
and therefore
that its value may be a trap value[1]; hence, in theory undefined
behaviour, but most likely to result in nonsense values. And AFAICT it's
_allowed_ to result in the same nonsense value no matter what you store
in bar.d, or even in different nonsense values even if you store the
same value in bar.d more than once.
There's a common misconception that reading a (non-character type)
union member other than the last member stored is automatically
undefined behavior. It isn't. Of course, it's possible to
get undefined behavior if there's a trap representation, but
if trap representations can be ruled out, the result is only
implementation defined behavior. For example,
union {
int i;
unsigned u;
} x;
x.i = 5;
return x.u;
must return the value 5.
.
- Prev by Date: Re: compile-time assertions
- Next by Date: Re: detab utility challenge (wrapping up).
- Previous by thread: Re: Finding out if a struct is in an array of structs
- Next by thread: Re: detabbing again
- Index(es):
Relevant Pages
|
Loading