▲ | jcranmer a day ago | |||||||||||||||||||||||||||||||
> punning through a union was legal in C In C89, it was implementation-defined. In C99, it was made expressly legal, but it was erroneously included in the list of undefined behavior annex. From C11 on, the annex was fixed. > but UB in C++ C++11 adopted "unrestricted unions", which added a concept of active members that is UB to access other members unless you make them active. Except active members rely on constructors and destructors, which primitive types don't have, so the standard isn't particularly clear on what happens here. The current consensus is that it's UB. C++20 added std::bit_cast which is a much safer interface to type punning than unions. > punning through incompatible pointer casting was UB in both There is a general rule that accessing an object through an 'incompatible' lvalue is illegal in both languages. In general, changing the const or volatile qualifier on the object is legal, as is reading via a different signed or unsigned variant, and char pointers can read anything. | ||||||||||||||||||||||||||||||||
▲ | trealira a day ago | parent | next [-] | |||||||||||||||||||||||||||||||
> In C99, it was made expressly legal, but it was erroneously included in the list of undefined behavior annex. In C99, union type punning was put under Annex J.1, which is unspecified behavior, not undefined behavior. Unspecified behavior is basically implementation-defined behavior, except that the implementor is not required to document the behavior. | ||||||||||||||||||||||||||||||||
| ||||||||||||||||||||||||||||||||
▲ | ryao a day ago | parent | prev [-] | |||||||||||||||||||||||||||||||
The GCC developers disagree as of last December: > Type punning via unions is undefined behavior in both c and c++. | ||||||||||||||||||||||||||||||||
|