Back to results for “Undefined Behavior”
C++ › Undefined Behavior

What is the strict aliasing rule and how can violating it cause UB?

Advanced

Answer

Strict aliasing says you generally may not access an object through a pointer/reference of an incompatible type (with some exceptions like char/std::byte). Violating it—e.g., reinterpreting a float* as an int* and reading through it—is UB, and compilers optimize assuming differently-typed pointers don't alias. Use std::bit_cast, memcpy, or unions carefully to reinterpret bytes safely.
float f=1.0f;
int i = *reinterpret_cast<int*>(&f);  // strict-aliasing UB
Real-world example A hand-rolled float-to-int bit hack breaks under optimization due to strict aliasing; std::bit_cast fixes it.

Common follow-ups: How do you legally reinterpret bytes? | Why do compilers assume no aliasing?