Type punning Vs Union member access

2019-07-04 02:17发布

问题:

As per this https://stackoverflow.com/a/1812932/1814023 writing one member of union and reading another member is undefined behavior.

And as per this https://stackoverflow.com/a/11640603/1814023 type punning is allowed in C99 / C11

I am bit confused on these two posts, which one is correct? Need help in understanding type punning Vs accessing the member of union.

Thanks.

回答1:

It's implementation-defined in C89:

C89 3.3.2.3 Structure and union members

With one exception, if a member of a union object is accessed after a value has been stored in a different member of the object, the behavior is implementation-defined. One special guarantee is made in order to simplify the use of unions: If a union contains several structures that share a common initial sequence, and if the union object currently contains one of these structures, it is permitted to inspect the common initial part of any of them. Two structures share a common initial sequence if corresponding members have compatible types for a sequence of one or more initial members.

In C99/C11, it's allowed, although when it's trap representation, the value is indeterminate.

C11 6.5.2.3 Structure and union members footnote

If the member used to read 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.