In C++20, why does `std::bit_cast<std::uint32_t>(gain)` work where `reinterpret_cast<std::uint32_t>(gain)` does not compile, and what does bit_cast require?
answer
- addresses versus values
- same size, trivially copyable
- returns a new object
- constexpr unless pointers or unions
basics
~10 sreinterpret_cast converts addresses, pointers and integers, never a float value, so the value form is ill-formed. std::bit_cast (C++20) copies the bits into a new object and needs equal sizes and trivially copyable types.
solid answer
~40 s`reinterpret_cast` has an exhaustive list of conversions, all about addresses: pointer to pointer, pointer to integer and back, function pointer types. A `float` value is not on it, so `reinterpret_cast<std::uint32_t>(gain)` is ill-formed; the pointer form `*reinterpret_cast<std::uint32_t*>(&gain)` compiles but reads a `float` through the wrong type, an aliasing violation. C++20's `std::bit_cast<To>(from)` in `<bit>` returns a new `To` whose bits equal `from`'s object representation. It requires `sizeof(To) == sizeof(From)` and both types trivially copyable, so mismatches fail to compile; it is `constexpr` unless a union, pointer, member pointer, volatile or reference member is involved, and invalid bit patterns for `To` are undefined. Before C++20 the idiom was `std::memcpy` into a local.
code
cpp · 16 lines#include <bit>
#include <cstdint>
#include <cstdio>
struct Sample { float gain; }; // trivially copyable, 4 bytes
constexpr std::uint32_t one_bits = std::bit_cast<std::uint32_t>(1.0f);
static_assert(one_bits == 0x3F800000); // evaluated at compile time
int main() {
float gain = -2.5f;
auto bits = std::bit_cast<std::uint32_t>(gain); // a new value, same bits
std::printf("%08X\n", static_cast<unsigned>(bits)); // C0200000
Sample s = std::bit_cast<Sample>(bits); // and back again
std::printf("%g\n", s.gain); // -2.5
}go deeper
Recall that reinterpret_cast works on pointers, and that C++20's std::bit_cast is how you get a float's bits as an integer.
Explain bit_cast's constraints, equal sizes and trivially copyable types, and why the pointer reinterpret_cast form is a different, riskier operation.
Replace pointer-cast punning in interop code with std::bit_cast or memcpy, and use bit_cast's constexpr support to check binary layouts at compile time.
Where the codebase cannot move to C++20, standardise one memcpy-based helper with the same contract, so the later switch to std::bit_cast is mechanical.
## Two different questions: addresses versus values A legacy plugin that ships audio gain as a raw 32-bit word forces the question "how do I get the bits of this `float` as a `std::uint32_t`?". C++ has two very different tools that people reach for. **`reinterpret_cast`** works on **addresses**. Its conversions are listed exhaustively in the draft: object pointers to other object pointers, references, pointers to integers and back, function pointers, member pointers. It never converts a **value**, so `reinterpret_cast<std::uint32_t>(gain)` with a `float gain` is ill-formed; Apple clang 21 reports "reinterpret_cast from 'float' to 'std::uint32_t' (aka 'unsigned int') is not allowed". What does compile, `*reinterpret_cast<std::uint32_t*>(&gain)`, converts the address and then reads a `float` object through a `std::uint32_t` lvalue, which the aliasing rule makes undefined; that rule is covered with type punning. **`std::bit_cast`** (C++20, header `<bit>`) works on **values**. It copies the object representation of one object into a new object of another type. ## The declaration and its contract ```cpp template<class To, class From> constexpr To bit_cast(const From& from) noexcept; ``` The draft constrains it to: - `sizeof(To) == sizeof(From)`; - `std::is_trivially_copyable_v<To>` and `std::is_trivially_copyable_v<From>`. It returns a new `To` object in which "each bit of the value representation of the result is equal to the corresponding bit in the object representation of from". Padding bits of the result are unspecified, and if the bits do not form a valid value of `To` (or of a subobject), the behaviour is undefined: `std::bit_cast<bool>(std::uint8_t{2})` is the classic case. Because the constraints are checked at compile time, a size mismatch is a compile error; libc++ expresses them as a `requires` clause, and the diagnostic says "because 'sizeof(unsigned long long) == sizeof(float)' (8 == 4) evaluated to false". ## Constant evaluation `std::bit_cast` is `constexpr`, which neither `reinterpret_cast` nor `std::memcpy` can be in a constant expression. So `static_assert(std::bit_cast<std::uint32_t>(1.0f) == 0x3F800000);` compiles. The C++23 wording makes it usable in constant expressions only when neither type, nor any of their subobjects, is: - a union; - a pointer or a pointer to member; - `volatile`-qualified; - a class with a non-static data member of reference type. C++26 restates this in terms of "constexpr-unknown representation" without changing the idea. Apple clang 21 rejects `constexpr auto p = std::bit_cast<std::uintptr_t>(&v);` with "bit_cast from a pointer type is not allowed in a constant expression". ## What `reinterpret_cast` is still for `std::bit_cast` does not replace `reinterpret_cast`; they answer different questions: | Need | Tool | |---|---| | bits of a value as another type | `std::bit_cast` (C++20), `std::memcpy` before C++20 | | a pointer as an integer, and back | `reinterpret_cast<std::uintptr_t>(p)` | | a C callback's function pointer type | `reinterpret_cast` between function pointer types | | view raw bytes of an object | `reinterpret_cast<const unsigned char*>` or `std::byte*` | A pointer converted to a large-enough integer and back to the same pointer type "will have its original value"; the integer's value itself is implementation-defined. Converting a function pointer to another function pointer type is allowed, but calling it through a type that does not match the definition is undefined. ## Byte order is not bit_cast's business `std::bit_cast` preserves the **object representation** exactly, so the bytes come out in the platform's own order. `std::bit_cast<std::array<std::byte, 4>>(word)` gives the bytes of a `std::uint32_t` least significant first on a little-endian machine and most significant first on a big-endian one. A plugin protocol that fixes a wire byte order still needs a conversion step: test `std::endian::native` against `std::endian::little` (C++20, `<bit>`) and swap with `std::byteswap` (C++23, `<bit>`) or with shifts and masks. ## Before C++20 The portable spelling was `std::memcpy(&bits, &gain, sizeof bits);` into a local, which compilers turn into a register move. `std::bit_cast` packages that idiom with three improvements: the size check is a compile error, it returns by value, and it works in constant expressions. ## What an interviewer listens for 1. `reinterpret_cast` converts addresses, not values, so the value form does not compile. 2. Reading the result of a pointer `reinterpret_cast` as a different type is the aliasing question, not a cast question. 3. `std::bit_cast` requires equal sizes and trivially copyable types, returns a new object, and is constexpr except for pointers, unions, volatile and reference members. 4. Byte order and invalid bit patterns remain the caller's problem: `std::bit_cast` copies bits, it neither validates nor reorders them.
- Is `std::bit_cast<float>(word)` safe for any 32-bit `word`?For IEEE 754 binary32 `float`, every 32-bit pattern is some value, including NaNs, so the call has a defined result. The danger is types with invalid patterns: `std::bit_cast<bool>` from a byte holding 2 is undefined, and a class with an enumeration or pointer member can receive values its own logic never produces.
- When is `reinterpret_cast` the right tool in a C plugin port?For address-level work: storing a pointer in a `std::uintptr_t` field and getting it back, converting between function pointer types a C loader returns, or viewing an object's bytes through `const unsigned char*` or `const std::byte*`. Each preserves or exposes an address; none reads an object as an unrelated type.
- reinterpret_cast<std::uint32_t>(f) returns the float's bit pattern.
- std::bit_cast returns a reference to the same object viewed as another type.
- std::bit_cast pads or truncates when the sizes differ.
- std::bit_cast works on any type, including std::string.
- std::bit_cast is usable in constant expressions for pointers too.
Assumes C++20 for std::bit_cast; its constant-evaluation limits are as worded in C++23, which C++26 rephrases without changing the idea.