skip to content

In C++, why is the fast inverse square root's `*(std::int32_t*)&y` read of a float undefined behaviour, and what is the legal rewrite?

level: middleimportance: must knowfreq 62%

answer

  1. which types may access an object
  2. a float is not an int32_t
  3. the compiler's type-based alias analysis
  4. copy the bits instead of reinterpreting
  5. bit_cast since C++20

basics

~20 s

The cast reads a float object through an int32_t glvalue, a type the strict aliasing rule does not allow, so the behaviour is undefined. Copy the bits instead: std::bit_cast in C++20, or std::memcpy before that.

solid answer

~50 s

C++'s **strict aliasing rule** ([basic.lval]) says an object's stored value may be accessed only through a glvalue of its own type (or a similar type), its signed or unsigned counterpart, or `char`, `unsigned char` or `std::byte`. `*(std::int32_t*)&y` reads a `float` through an `int32_t` lvalue, so it is undefined behaviour; the cast itself is fine, the access is not. Compilers use the rule for **type-based alias analysis**: they assume a store to an `int32_t` cannot change a `float`, which lets them reorder or delete loads, and a punned read can see a stale value once inlined. The legal rewrite copies the object representation into a new object: `std::bit_cast<std::uint32_t>(y)` in C++20, which also checks at compile time that both types are trivially copyable and the same size, or `std::memcpy(&i, &y, sizeof i)` in earlier standards. Optimising compilers turn both into a single register move.

code

cpp · 12 lines
cpp
#include <cstdint>
#include <cstdio>

float q_rsqrt(float number) {
    float y = number;
    std::int32_t i = *reinterpret_cast<std::int32_t*>(&y);   // UB: reads a float as int32_t
    i = 0x5f3759df - (i >> 1);
    y = *reinterpret_cast<float*>(&i);                       // UB: reads an int32_t as float
    return y * (1.5f - 0.5f * number * y * y);
}

int main() { std::printf("%f\n", q_rsqrt(4.0f)); }

go deeper

for a junior

Recall that reading a float through an int pointer is undefined behaviour in C++, and that std::memcpy or std::bit_cast is the safe way to get its bits.

for a middle

Explain the strict aliasing list, that the access rather than the cast is undefined, and why bit_cast and memcpy cost nothing after optimisation.

for a senior

Show how type-based alias analysis turns a punned access into a release-only bug, and catch the hidden size mismatch that bit_cast's constraints reject.

for a principal

Set a team rule that bit reinterpretation goes through one helper built on std::bit_cast, so reviewers never have to judge a cast's aliasing legality.

## The original code and what it does The well-known fast inverse square root approximates `1/sqrt(x)` by treating the bits of an IEEE-754 `float` as an integer, subtracting from a magic constant, and turning the result back into a `float`: ```cpp float y = number; long i = *(long*)&y; // reinterpret the float's bits as an integer i = 0x5f3759df - (i >> 1); y = *(float*)&i; // reinterpret the integer's bits as a float ``` The arithmetic trick is sound. The way it reads the bits is not, in C++ (and in C). ## The strict aliasing rule The standard ([basic.lval]; C++26 calls it being **type-accessible**) lists the only glvalue types through which an object of dynamic type `T` may have its stored value accessed: - `T` itself, or a type **similar** to it (differing only in cv-qualification at each level); - the signed or unsigned type corresponding to `T`; - `char`, `unsigned char` or `std::byte`. Any other access is **undefined behaviour**. A `float` read through `long` or `std::int32_t` matches none of them. Note that the `reinterpret_cast` (or C-style cast) is not the problem: converting the pointer is allowed. Dereferencing it to read the `float` is. There is a second, independent bug in the original: on LP64 platforms `long` is 64 bits, so `*(long*)&y` reads four bytes past the `float`. ## Why compilers care The rule exists so the optimiser can do **type-based alias analysis (TBAA)**. If a function receives an `int*` and a `float*`, the compiler may assume a store through one never changes what the other points to. It can keep values in registers across stores, reorder loads and stores, and vectorise loops. GCC enables this assumption with `-fstrict-aliasing` at `-O2`, `-O3` and `-Os`; Clang enables it by default except on Windows MSVC and UEFI targets. Code that breaks the rule can therefore work at `-O0` and fail at `-O2`, or fail only after a function is inlined into a new caller. ## The legal rewrites | Technique | Standard | Notes | |---|---|---| | `std::bit_cast<To>(from)` | C++20, header `<bit>` | returns a new `To` holding the same bits; constrained to trivially copyable types of equal size; usable in constant expressions for most types | | `std::memcpy(&to, &from, sizeof to)` | all standards | copies the object representation; needs a `static_assert` on the sizes | | union member punning | none in ISO C++ | undefined behaviour, though GCC documents it as an extension | The size constraint on `std::bit_cast` catches the original `long` bug at compile time: Clang 21 rejects `std::bit_cast<long>(y)` because `sizeof(long) == sizeof(float)` is false on an LP64 target such as this one. ## Cost Neither rewrite costs anything at `-O2`. Compilers recognise a small fixed-size `memcpy` and emit a plain register move; on AArch64 the `memcpy` version of the function compiles to an `fmov` from the floating-point register to an integer register and back, with no call. `std::bit_cast` lowers to the same instructions. ## Spotting it in review Type punning hides in more shapes than the textbook cast. Look for: - `*(T*)&x` or `*reinterpret_cast<T*>(&x)` where `T` is unrelated to the type of `x`; - `reinterpret_cast<T&>(x)`, which is the same access spelled as a reference; - a `struct Vec3 { float x, y, z; }` passed to an API as `float*` and indexed past the first member; - an array of one integer type read through a pointer to another integer type of a different size, such as `std::uint32_t*` over `std::uint16_t` data; - "works in debug, wrong in release" reports in numeric code, especially after a compiler upgrade or after a function became inlinable. Each of these is a candidate for a `std::bit_cast` or `memcpy` rewrite; the signed and unsigned variants of the same integer type are the one integer mix that is allowed. ## What to say in an interview 1. Name the rule: an object may be accessed only through its own type, its signed or unsigned variant, or a character type or `std::byte`. 2. Say where the undefined behaviour is: the dereference, not the cast. 3. Explain why it matters: type-based alias analysis lets the optimiser assume the accesses do not overlap. 4. Give the fix for the standard in use: `std::bit_cast` in C++20, `std::memcpy` before, and mention that both compile to the same code.

  • Why does std::bit_cast require both types to be trivially copyable?
    It creates a new object whose value representation is a copy of the source's bytes. That is only meaningful for types whose state is entirely their bytes, which is what trivially copyable means: no user-provided copy or move operations that maintain invariants. Copying the bytes of a `std::string`, for example, would duplicate an owning pointer.
  • Is `reinterpret_cast<std::uint32_t&>(y)` any better than the pointer cast?
    No. A reference cast is defined in terms of the same pointer cast, and reading through the resulting `std::uint32_t&` accesses the `float` through an `std::uint32_t` glvalue, which strict aliasing forbids. Changing the spelling of the cast never changes the access.

  • reinterpret_cast is the legal way to reinterpret bits, that is what it is for.
  • The cast itself is undefined behaviour, not the read through it.
  • memcpy is slower than a pointer cast because it calls a library function.
  • It is fine because int32_t and float have the same size.
  • Strict aliasing only matters in C, not in C++.

Assumes C++20 or later for std::bit_cast (header <bit>); in C++17 and earlier std::memcpy is the portable rewrite.