James Kuyper
9/8/2011 4:39:00 PM
On 09/08/2011 12:28 PM, Kenneth Brody wrote:
> Okay, I can't find C&V, but as I recall, accessing a union via anything
> other than the one last written to is UB. For example:
Footnote 82 indicates that
> If the member used to access the contents of a union object is not the same as the member last used to
> store a value in the object, the appropriate part of the object representation of the value is reinterpreted
> as an object representation in the new type as described in 6.2.6 (a process sometimes called "type
> punning"). This might be a trap representation.
However, there doesn't seem to be any normative text to support this
footnote. At least, I didn't find the term "reinterpret" anywhere else
in the document.
> my_union.my_int = i;
> f = my_union.my_float;
>
> However, I believe that you can always access "legal" memory via an unsigned
> char pointer.
>
> So, what if the union contains an unsigned char array, as in:
>
> union foobar {
> unsigned char raw[MY_UNION_SIZE];
> some_type foo;
> other_type bar;
> };
>
> Are all values in the raw[] array guaranteed to be readable? (It "works" on
> all platforms I have tried, but is that guaranteed? I'm pretty sure it is,
> but I can't find C&V.)
The only potential problem would be if they contained a trap
representation, but unsigned char is not allowed to have trap
representations.