A pointer cast that works at -O0 but silently breaks at -O2

Type Punning in C and C++

Type punning—reinterpreting memory as different types—is essential for serialization and low-level work, but pointer casts are undefined behavior under strict aliasing rules. The author recounts a bug where a float* to uint32_t* cast ran fine at -O0 and silently failed at -O2. The safe alternatives are unions and memcpy, both of which compilers optimize to single instructions.

The problem is that “works in practice” and “has defined behaviour” are different things.
  1. eqvinox

    The example included below "Why C and C++ Differ" is UB in both C and C++ (and says nothing about "why" C & C++ differ). The article isn't overall wrong but that bit is just...

    (Feels a bit like LLM junk, but honestly not sure.)

  2. scoopr

    I just watched video[0] that argues if you can consteval something, then it must be free of UB, which seems compelling, at least for these lower level helpers.

    Unfortunately, it seems memcpy is not constexpr, so cannot be used like this, but std::bit_cast actually works[1] as constexpr, so I think in C++ that would now be the most preferred use. It won't allow the union either.

    [0] https://www.youtube.com/watch?v=-LAXqqqX274

    [1] https://godbolt.org/z/xGzjTMGvv

  3. antiloper

    > The C vs C++ distinction here is genuinely treacherous

    What's so genuine about this?

More from this day

2026-09-22