Type Punning in C and C++
2 hours ago
- Type punning is interpreting memory as different types between reads and writes, essential for serialization, network protocols, and low-level hardware access.
- In C, safe type punning methods are unions and memcpy, which have defined behavior.
- Pointer casts for type punning are technically undefined behavior in both C and C++ due to strict aliasing rules, even though they often work in practice.
- C and C++ differ in how the compiler treats types; C++ assumes different types never alias, leading to more aggressive optimizations that can break code relying on type punning.
- The practical rule is to use unions or memcpy for type punning in C and C++ to ensure defined behavior and avoid silent bugs.
- A common issue is that pointer casts can work at -O0 but break at -O2 due to compiler optimizations based on strict aliasing.
- The article uses an example showing how the compiler optimizes away checks when types are assumed not to alias, potentially returning incorrect results.