97. Don’t use unions to reinterpret representation

Summary

A deceit is still a lie: Unions can be abused into obtaining a “cast without a cast” by writing one member and reading another. This is more insidious and even less predictable than reinterpret_cast (see Item 92).

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 ...

Get C++ Coding Standards: 101 Rules, Guidelines, and Best Practices now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.