DiscussionDon't read a field of a union unless it was the field that was last written. Reading a different field of a union than the field that was last written has undefined behavior, and is even worse than doing a reinterpret_cast (see Item 92); at least with the latter the compiler has the fighting chance to warn and repel an "impossible reinterpretation" such as pointer to char. When abusing a union, no reinterpretation of bits will ever yield a compile-time error or a reliable result. Consider this code that is intended to deposit a value of one type (char*) and extract the bits of that value as a different type (long): union { long intValue_; char* pointerValue_; }; pointerValue_ = somePointer; long int gotcha = intValue_; This has two problems:
![]() |