Discussion
Don'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:
- It assumes too much:
It assumes that sizeof(long) and sizeof(char*) are equal, and that the bit representations are identical. These things are not true on all implementations (see Item 91). - It obscures your intent for both human readers and compilers:
Playing union games makes it harder for compilers to catch genuine type errors, and for humans to spot logical errors, than even the infamous reinterpret_cast (see Item 92).