Octocontrabass wrote:
Type punning through pointers is undefined behavior. (Type punning through unions is also undefined behavior, but GCC and Clang allow it as an extension.)
The first statement is mostly correct, since it breaks the strict aliasing rule, unless you type pun to a character type (since pointers to character type are allowed to alias all objects).
The second is wrong in C. In C99, footnote 82 defines the behavior:
C99 wrote:
82) 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.
An earlier draft still contained language saying this was implementation-defined, but that did not make it into the final C99 standard. And even that would explicitly contradict your assertion that it is undefined.
C11 retains the same footnote, although it is now footnote 95. C18 also retains the footnote, it is now footnote 97.
C++ appears to be more restrictive about that, although in the draft standard I looked at, they never straight up come out and say it. They say that at most one data member of a union can be active at any time, but never what that means. There is no sentence like "reads from a non-active data member are ill-formed" or anything. But C++ does not have the above footnote or anything like it.