T
Tim Rentsch
James Kuyper said:I don't know how you reached that conclusion. My only use of the word
undefined' in the text you quoted was in reference to accessing a trap
representation. Accessing a union member other than the one last
stored doesn't automatically guarantee that a trap representation is
present; indeed, for some types a trap representation is impossible,
either because the standard says so, or because those types are
so-defined by the particular implementation you're using. Even if a
trap representation is possible, it's presence is not guaranteed.
Note: plain 'int' is NOT one of the types for which the standard
prohibits trap representations.
If a trap representation is possible, accessing a union member other
than the one last written to is indeed one way in which it can
occur. Type-punning and using memcpy() in the way that I did are two
other ways this can happen; they're all roughly equally likely to
fail, for pretty much the same reasons. On an implementation where any
one of them are safe, they'll probably all be safe, but the standard
allows implementations where none of them are safe.
For practical purposes, it doesn't matter whether undefined behavior
is guaranteed, or merely a possibility - in either case, the correct
response to becoming aware of that fact is to fix the code.
Yes, accessing a trap representation is always undefined behavior.
My point was, if the presence of a trap representation can be
ruled out, which it frequently can, then accessing a union member
other than the last one stored into behaves in a well-defined way.
(Here well-defined includes unspecified and implementation-defined
values, but still defined rather than undefined.)
My apologies if I misunderstood or misrepresented your position.