skip to content

How do you describe a memory-mapped UART register block in C++, and why are bit-fields a risky way to name its bits?

level: middleimportance: should knowfreq 45%

answer

  1. a struct of volatile words
  2. reinterpret_cast is not constexpr
  3. static_assert the offsets
  4. bit-field allocation is implementation-defined
  5. masks plus std::byte for data

basics

~20 s

Model the block as a struct of volatile fixed-width words, check offsets with static_assert, and reach it through a pointer made by reinterpret_cast from the address. Name bits with mask constants, because bit-field layout and access width are implementation-defined.

solid answer

~40 s

A register block is usually a struct whose members are `volatile std::uint32_t`, laid out to match the reference manual and checked with `static_assert(offsetof(UartRegs, CR1) == 0x0C)`. Code reaches it through `reinterpret_cast<UartRegs*>(0x4001'1000)`, wrapped in an inline function, because `reinterpret_cast` is not allowed in a constant expression, so the pointer cannot be a `constexpr` variable. Bits are named with `constexpr` masks such as `1u << 5`. Bit-fields look tidier, but the standard makes the allocation and alignment of bit-fields implementation-defined: bit order, straddling and the width of the access the compiler uses all depend on the ABI, so the same struct can map to different bits on another toolchain, and a write to one bit-field reads and rewrites its neighbours. For raw received data, `std::byte` (C++17) says these are bytes, not numbers.

code

cpp · 29 lines
cpp
#include <cstddef>
#include <cstdint>
#include <cstdio>

struct UartRegs {                 // layout from the reference manual
  volatile std::uint32_t SR;      // 0x00 status
  volatile std::uint32_t DR;      // 0x04 data
  volatile std::uint32_t BRR;     // 0x08 baud rate
  volatile std::uint32_t CR1;     // 0x0C control
};
static_assert(offsetof(UartRegs, CR1) == 0x0C);
static_assert(sizeof(UartRegs) == 0x10);

constexpr std::uint32_t SR_RXNE = 1u << 5;   // receive register not empty
constexpr std::uint32_t CR1_UE  = 1u << 13;  // UART enable

// On the device: reinterpret_cast<UartRegs*>(0x4001'1000). Here a static object stands in.
UartRegs fake_uart{};
inline UartRegs& uart1() { return fake_uart; }

int main() {
  uart1().CR1 = uart1().CR1 | CR1_UE;          // read-modify-write as two accesses
  uart1().DR = 0x41;                            // pretend a byte arrived
  uart1().SR = SR_RXNE;
  if (uart1().SR & SR_RXNE) {
    std::byte b{static_cast<unsigned char>(uart1().DR)};
    std::printf("CR1=0x%x byte=%d\n", static_cast<unsigned>(uart1().CR1), std::to_integer<int>(b));
  }
}

go deeper

for a junior

Know the shape: a struct of volatile fixed-width registers reached through a pointer cast from the peripheral's address.

for a middle

Explain why the pointer cannot be constexpr, how static_assert pins the layout, and why masks beat bit-fields.

for a senior

Reason about access width and write-1-to-clear bits, and when one toolchain's documented bit-field ABI is acceptable.

for a principal

Choose between vendor headers, generated register maps and hand-written structs, and set the review rules for each.

## A register block as a struct A microcontroller's reference manual lists each peripheral as a base address and a table of registers at fixed offsets. The usual C++ model mirrors that table: ```cpp struct UartRegs { volatile std::uint32_t SR; // 0x00 status volatile std::uint32_t DR; // 0x04 data volatile std::uint32_t BRR; // 0x08 baud rate volatile std::uint32_t CR1; // 0x0C control }; static_assert(offsetof(UartRegs, CR1) == 0x0C); static_assert(sizeof(UartRegs) == 0x10); ``` Key points: - **Fixed-width types** from `<cstdint>` so each member is exactly the register's width. - **`volatile` on the members** (or on the pointer's pointee type) so every access is performed. - **`static_assert` on `offsetof` and `sizeof`** turns a padding or typing mistake into a compile error instead of a write to the wrong register. The struct is standard-layout, so `offsetof` is well defined. ## Getting a pointer to it The block lives at an address such as `0x4001'1000`. The conversion from an integer to a pointer is a `reinterpret_cast`, and that is where people trip: ```cpp constexpr auto* uart1 = reinterpret_cast<UartRegs*>(0x4001'1000); // error ``` Clang rejects such a declaration with an error that the constexpr variable must be initialized by a constant expression, and the note `reinterpret_cast is not allowed in a constant expression`: the rules for core constant expressions exclude `reinterpret_cast`. The usual forms are an `inline` function returning `*reinterpret_cast<UartRegs*>(0x4001'1000)`, a non-constexpr global pointer, or a linker-placed object. All of them compile to a constant address load at `-O2`. ## Why bit-fields are risky here A bit-field such as `unsigned rxne : 1;` looks like a perfect way to name a status bit. The standard says otherwise: 1. **Allocation is implementation-defined.** Whether the first bit-field takes the lowest or highest bit, and whether a field can straddle an allocation unit, depends on the implementation; the standard's own note says bit-fields are assigned right-to-left on some machines and left-to-right on others. 2. **Alignment is implementation-defined**, so padding between fields is not portable either. 3. **Access width is not yours to choose.** Writing one bit-field is a read-modify-write of whatever unit the compiler picks, which may be a byte or half-word access to a register that only accepts 32-bit accesses, and it rewrites the neighbouring bits with the values just read. A status register with write-1-to-clear bits can be cleared by accident. 4. **No address.** `&regs.mode` is ill-formed; Clang reports `address of bit-field requested`. A given ABI does pin these choices down, and some vendor headers use bit-fields knowingly for one compiler. Portable code names bits with masks and shifts instead: ```cpp constexpr std::uint32_t SR_RXNE = 1u << 5; if (uart1().SR & SR_RXNE) { /* a byte is waiting */ } ``` Masks are obvious in a code review, the access width is that of the volatile member, and nothing depends on bit allocation. ## std::byte for the data path The received data are bytes, not numbers. `std::byte` (C++17) is declared as `enum class byte : unsigned char {}`: it supports the bitwise operators and shifts but no arithmetic, converts to an integer only through `std::to_integer<IntType>`, and, like `unsigned char`, may be used to examine any object's bytes. A receive buffer declared as `std::byte rx_buf[64]` cannot be added to an integer by accident. ## Vendor headers and generated maps Most projects do not write register structs by hand. Chip vendors ship device headers, and many toolchains generate register maps from a machine-readable description of the chip. The C++ points above are how to review them: check that members are `volatile` and fixed-width, that layouts are pinned by `static_assert` or by the generator's own tests, and whether the header relies on one compiler's bit-field ABI. A generated C++ wrapper can also make illegal accesses impossible, for example by giving read-only registers no assignment operator. ## Checklist for a register map | Item | Choice | |---|---| | Member type | `volatile std::uint32_t` (or the register's width) | | Layout check | `static_assert` on every `offsetof` and the `sizeof` | | Base address | inline accessor around `reinterpret_cast` | | Bit names | `constexpr` masks, not bit-fields | | Data bytes | `std::byte` or `std::uint8_t` |

  • Why does writing one bit-field of a hardware register risk clearing other bits?
    Assigning a bit-field is a read-modify-write of the unit that holds it: the compiler loads the unit, changes the field and stores the whole unit back. If the register has write-1-to-clear status bits, writing back a 1 that was just read clears them. The access width the compiler picks may also be one the peripheral rejects.
  • How do you make the register struct's layout a compile-time guarantee?
    Add `static_assert(offsetof(UartRegs, BRR) == 0x08)` for every member and `static_assert(sizeof(UartRegs) == 0x10)` for the whole block. A wrong type, a missing member or unexpected padding then fails the build instead of writing to the wrong address.

  • Bit-field bit order is fixed by the C++ standard.
  • A constexpr pointer to a register can be made with reinterpret_cast.
  • Writing one bit-field touches only that field's bits in hardware.
  • std::byte supports arithmetic like unsigned char does.
  • Register structs need no layout checks if the members are volatile.