skip to content

In C++, is writing one union member and then reading another a legal way to reinterpret a float's bits, given that C allows it?

level: seniorimportance: should knowfreq 50%

answer

  1. only one member is active
  2. C and C++ differ here
  3. a compiler extension, not the standard
  4. constant evaluation refuses it
  5. bit_cast states the intent

basics

~20 s

No. In C++ only the most recently written union member is within its lifetime, so reading another member is undefined behaviour. GCC documents union punning as an extension; portable C++ uses std::bit_cast (C++20) or std::memcpy.

solid answer

~50 s

A C++ union has at most one **active member**: the one whose lifetime has begun and not ended. Writing `fb.f = x` makes `f` active; reading `fb.u` then accesses an object that is not within its lifetime, which is undefined behaviour. C defines this as reinterpreting the bytes, and C++ does not. GCC's manual says type-punning through a union is undefined in ISO C++ but supported as an extension, provided the access goes through the union type; taking `&fb.u` and reading through the pointer is not covered. Constant evaluation enforces the ISO rule: Clang rejects the same read in a `constexpr` context with 'read of member 'u' of union with active member 'f' is not allowed in a constant expression'. The one standard exception is the **common initial sequence** of standard-layout structs in a union. The portable rewrite is `std::bit_cast<std::uint32_t>(x)` in C++20, which is also `constexpr`, or `std::memcpy` before C++20.

code

cpp · 22 lines
cpp
#include <bit>
#include <cstdint>
#include <cstdio>

union FloatBits {
    float f;
    std::uint32_t u;
};

std::uint32_t bits_union(float x) {
    FloatBits fb;
    fb.f = x;          // f becomes the active member
    return fb.u;       // UB in ISO C++: u is not within its lifetime
}

constexpr std::uint32_t bits_cast(float x) {
    return std::bit_cast<std::uint32_t>(x);   // C++20, also usable in constant expressions
}

int main() {
    std::printf("%08x %08x\n", bits_union(1.0f), bits_cast(1.0f));
}

go deeper

for a junior

Recall that a union holds one member at a time and that reading a different member than the one written is not portable C++.

for a middle

Explain the active member rule, how C differs, and why std::bit_cast or std::memcpy is the portable replacement.

for a senior

Separate the ISO rule from GCC's documented extension and its limits, and use constexpr evaluation and the common initial sequence rule to argue precisely.

for a principal

Decide whether legacy union punning is migrated or formally tied to a compiler extension, and make that dependency visible in the build requirements.

## What the standard says about unions In C++ a union stores at most one member at a time. The standard ([class.union]) defines a member as **active** when its name refers to an object whose lifetime has begun and not ended, and states that at most one member can be active at any time. Assigning to `fb.f` starts the lifetime of the `float` member; the `std::uint32_t` member is not alive. Reading `fb.u` at that point reads an object outside its lifetime. That is **undefined behaviour**, regardless of the fact that both members occupy the same bytes. C++ has no rule that reinterprets the bytes on a read of the inactive member. C is different: it specifies that reading a member other than the last one written reinterprets the relevant bytes as the new type. Code that moves from C to C++ therefore changes meaning without changing a character. ## What compilers actually promise The ISO rule and the compilers' documented behaviour differ, and an interviewer will expect you to know both: - **GCC** documents, under `-fstrict-aliasing`, that "In ISO C++, type-punning through a union type is undefined behavior, but GCC supports it as an extension", and adds that it works only when the memory is accessed through the union type. Taking `int* ip = &t.i;` and reading through `ip` "might not" work, and casting a `double*` to a union pointer is undefined. - **Constant evaluation** follows ISO strictly. The standard lists reading a non-active union member among the things a core constant expression may not do, so where a constant is required the compiler must reject it; Clang 21 does: "read of member 'u' of union with active member 'f' is not allowed in a constant expression". - Behaviour that a compiler documents as an extension binds that compiler only. Code relying on it is portable only to compilers that make the same promise. ## The one standard exception The standard does define reading through an inactive member in one case. If a **standard-layout union** contains several **standard-layout structs** that share a **common initial sequence** (the same leading member types), and one of those structs is active, the common initial members may be read through any of them. This supports the "tagged message" pattern: ```cpp struct Ping { int kind; int seq; }; struct Data { int kind; int length; }; union Msg { Ping ping; Data data; }; // if msg.ping is active, msg.data.kind may be read: kind is in the common initial sequence ``` It does not cover a `float` and an integer, which share no struct prefix. ## Why C++ cannot simply adopt C's rule C's rule fits a language in which every object is plain bytes. C++ unions may hold members with constructors and destructors, such as a `std::string`, and the language tracks which member's lifetime has begun so that the right destructor can run and so that constant evaluation can reason about the union. Several consequences follow: - changing the active member of a union with non-trivial members requires explicitly destroying the old member and constructing the new one, usually with placement new; - a union with a member that has a non-trivial copy constructor gets an implicitly deleted copy constructor unless it provides its own, because copying bytes would be meaningless for that member; - the optimiser may assume that a value written to one member is not observed through another, which is the same assumption type-based alias analysis makes. Reinterpreting bytes on a read would cut across all of these, so the standard leaves it undefined and provides `std::bit_cast` for the legitimate use case. ## Comparing the three techniques | Technique | ISO C++ status | Constant expressions | Notes | |---|---|---|---| | union member read | undefined (except common initial sequence) | rejected | GCC extension when accessed through the union | | `std::memcpy` into a new object | defined | not usable | any standard; small copies become register moves | | `std::bit_cast` | defined, C++20 | usable for most types | checks equal size and trivial copyability at compile time | ## Advice for real code 1. Replace union punning with `std::bit_cast` in C++20 code, or a small `memcpy`-based helper in older code. 2. Keep unions for their real job: storing one of several alternatives, ideally wrapped in `std::variant`, which tracks the active alternative for you. 3. When porting C code that puns through unions, list every such site; the C semantics will not follow it into C++. 4. If a legacy codebase depends on the GCC extension, record that dependency next to the compiler requirements rather than leaving it implicit.

  • Why can a compiler that supports union punning at run time still reject it in constexpr code?
    Constant evaluation must diagnose undefined behaviour instead of guessing. The standard defines what a constant expression may do, and reading an inactive union member is not on that list. A run-time extension is the compiler's promise about generated code; it does not change what the language allows during constant evaluation.
  • Does std::variant let you read the bits of one alternative as another?
    No. std::variant tracks which alternative is active and `std::get` with the wrong alternative throws `std::bad_variant_access`. It is the safe replacement for a tagged union, not a punning tool; for bit reinterpretation use `std::bit_cast` or `std::memcpy`.

  • Union punning is defined in C++ because it is defined in C.
  • Both members share the same storage, so reading either one is fine.
  • If it works with GCC, the standard must allow it.
  • Taking the inactive member's address and reading through the pointer is the same as reading the member.
  • std::bit_cast is just a union-based helper in disguise.

Assumes C++20 or later for std::bit_cast; the union rule itself is the same in every C++ standard.