Keith Thompson said:
I believe so, yes. At least I can't think of a way a conforming
implementation could avoid it. (I'll assume u is an object of type
"union u".)
# 6.7.2.1
# 14 [...] The value of at most one of the members can be stored in
# a union object at any time. [...]
It says that after you store a value into a union members, all other
members don't have a value, so it must be UB to read through them.
In the absence of other rules, I believe it gives the compiler license
to assume that for value reading, different member-access expressions
cannot alias. This means that a union could be treated as a struct, with
the exception that for representation purposes the members must lie
at the beginning of the object.
I'm not sure how relevant this is (ie. how much the Readers are aware of
this): In the draft n869.txt in 6.5.2.3#5, the first sentence "With one
exception, if the value of a member of a union object is used when the
most recent store to the object was to a different member, the behavior
is implementation-defined.70)" is *not* in the C99 Standard (but I see
it in C89 draft, so it must have been in C89.).
I'm aware of a point in Annex J.1, which lists as unspecified:
# -- The value of a union member other than the last one stored
# into (6.2.6.1).
IMHO it is wrong: 6.2.6.1p7 is talking about the representation of a
union object, and does not give the complete semantics of member access.
I have looked through an amount of posts from the last years. I don't
give any specific references, it's enough to say that opinions varied to
the extremes. Eg. C.Feather at the exactly same case as the discussed
above one, said it was defined (it's undefined if union members are
incompatible); at another occasion Dan Pop said one could read only the
last written-to member, with an exception of character members; at yet
another time Doug Gwyn said reading a not-last-written-to union member
was meant to be undefined (but his remark was in a context where two
fields were incompatible, so I couldn't judge how far conclusions could
be drawn).
(I suggest, can we add c.s.c. to the discussion?)