skip to content

Embedded and Freestanding

Firmware and some engines build C++ without exceptions, RTTI or a heap, and talk to hardware through registers. Interviewers ask what changes when those features are off.

on this pageshow

explore

questions

14

In C++, what does volatile guarantee when a UART driver polls a memory-mapped status register, and what can go wrong without it?

level: juniorimportance: must knowfreq 70%

answer

  1. the value changes behind the compiler
  2. every access is observable behaviour
  3. no caching in a register
  4. an empty loop may vanish

basics

~20 s

volatile makes every read and write of the register an observable side effect, so the compiler must perform each access the source asks for. Without it the compiler may read the status once, or delete the polling loop entirely.

solid answer

~50 s

A memory-mapped status register changes because hardware writes it, which the compiler cannot see. In C++ an access through a `volatile` glvalue is a side effect and part of the program's observable behaviour, so the compiler must perform each read and write the source contains, in source order relative to other volatile accesses. Without `volatile`, the compiler may assume a plain object only changes when the program writes it: a `while ((sr & RXNE) == 0) {}` loop can be reduced to one read, and because a loop with no observable effects may be assumed to terminate, Clang at -O2 compiled such a loop to a bare return. `volatile` does not make an access atomic, does not order it against non-volatile memory, and does not emit fences; what an access means in hardware terms is implementation-defined.

code

plaintext · 20 lines
plaintext
_Z10wait_plainv:                        @ while ((plain_sr & 0x20u) == 0) {}
	bx	lr
_Z8wait_volv:                           @ while ((vol_sr & 0x20u) == 0) {}
	movw	r0, :lower16:vol_sr
	movt	r0, :upper16:vol_sr
	b	.LBB1_2
	ldr	r1, [r0]
	lsls	r1, r1, #26
	it	mi
	bxmi	lr
	ldr	r1, [r0]
	lsls	r1, r1, #26
	bmi	.LBB1_4
	ldr	r1, [r0]
	lsls	r1, r1, #26
	itt	pl
	ldrpl	r1, [r0]
	lslspl.w	r1, r1, #26
	bpl	.LBB1_1
	bx	lr

go deeper

for a junior

Say that volatile forces each read and write of a hardware register to happen, so a polling loop really re-reads it.

for a middle

Explain observable behaviour and why the optimizer may delete a loop over a plain variable, citing the forward-progress rule.

for a senior

Spell out what volatile does not give, atomicity, ordering and fences, and pick atomics or barriers where the driver needs them.

for a principal

Set the rule for the codebase: volatile only inside register accessors, never as a synchronization tool, with review checks to enforce it.

## The problem volatile solves On a microcontroller the UART's status register is not ordinary memory. It sits at a fixed address, and the peripheral sets its **RXNE** bit when a byte arrives. From the compiler's point of view the code that waits for that bit looks like this: ```cpp extern volatile std::uint32_t vol_sr; // stands in for *reinterpret_cast<volatile std::uint32_t*>(0x40011000) void wait_for_byte() { while ((vol_sr & 0x20u) == 0) {} } ``` Nothing in the program writes `vol_sr`. If it were a plain `std::uint32_t`, the optimizer would be entitled to assume its value never changes during the loop, because a change from another thread without synchronization would be a data race, and a data race is undefined behaviour. ## What the standard actually promises Three pieces of wording carry the guarantee: - Reading an object through a **volatile glvalue** (an lvalue or xvalue of volatile-qualified type) is a **side effect**, like modifying an object or calling an I/O function. - The **observable behaviour** that a conforming implementation must reproduce includes the rule that accesses through volatile glvalues are evaluated strictly according to the rules of the abstract machine. Two volatile reads in the source are two reads in the program, in that order. - The **forward-progress** rule lets the implementation assume a thread eventually terminates, performs I/O, performs an access through a volatile glvalue, or performs an atomic or synchronization operation. A polling loop that reads a volatile object is making progress; the same loop over a plain variable is not, and the compiler may assume it ends. The standard also says the semantics of a volatile access are **implementation-defined**, and a note explains the intent: `volatile` is a hint to avoid aggressive optimization because the value can change by means the implementation cannot detect, with semantics intended to match C. On a typical microcontroller toolchain that means a single load or store instruction of the declared width. ## What happens without it The code example below is Clang 21 output for a Cortex-M target at `-O2`, with the same loop written over a plain and over a volatile variable. The plain version is a single `bx lr`, a return: the compiler read nothing at all, because either the bit is already set or the loop would spin forever without side effects, which it may assume does not happen. The volatile version loads the register on every iteration. On real hardware the plain version returns before any byte has arrived, and the driver then reads garbage from the data register. ## Reading a register on purpose Because every volatile access really happens, it also matters how many you write. Many peripherals have **side effects on read**: reading the UART data register typically clears the receive flag, and some status bits clear when read. Two habits follow: - Read a status register once into a local (`const auto sr = uart.SR;`) and test several bits on the copy, instead of writing `uart.SR & A` and `uart.SR & B`, which is two hardware reads that can see different values. - Never read a data register "just to look" in a debug print; the byte is consumed. ## What volatile does not do Interview follow-ups usually probe the limits, and they matter more than the guarantee: 1. **No atomicity.** `++counter` on a volatile object is still a load, an add and a store; an interrupt between them loses an update. 2. **No ordering against ordinary memory.** The compiler may move a non-volatile store across a volatile access, so a flag in a volatile variable does not publish a buffer written with plain stores. 3. **No hardware fences.** On a core with a write buffer or out-of-order memory, `volatile` emits no barrier instruction. 4. **Not for thread synchronization.** Between threads, use `std::atomic` and the standard library's synchronization; `volatile` gives no happens-before relation. ## Where volatile belongs | Use | Right tool | |---|---| | Memory-mapped register | `volatile` access of the register's width | | Byte shared with an interrupt handler | `std::atomic` that is lock-free | | Flag shared with a signal handler | `volatile std::sig_atomic_t` or a lock-free `std::atomic` | | Data shared between threads | `std::atomic`, `std::mutex` | Also remember the rule in the other direction: accessing an object **defined** as volatile through a non-volatile glvalue, for example by casting the qualifier away, is undefined behaviour.

  • Why is it undefined behaviour to cast volatile away and poll the register through a plain pointer?
    The standard says that accessing an object defined with a volatile-qualified type through a non-volatile glvalue is undefined behaviour. In practice the compiler then treats the reads as ordinary loads it may merge or hoist, which is exactly the bug `volatile` was there to prevent.
  • Does volatile stop the CPU itself from reordering or buffering register writes?
    No. `volatile` constrains the compiler only: it keeps each access and their order in the generated code. A core with a write buffer can still delay a store to a peripheral; making it reach the device first needs the architecture's barrier instruction, issued through an intrinsic or inline assembly.

  • volatile makes a read-modify-write of the register atomic.
  • volatile inserts a memory barrier instruction around each access.
  • volatile orders a plain buffer write before a later volatile store.
  • Without volatile the compiler still re-reads memory inside every loop.
  • volatile is the right tool for data shared between threads.
open as a page

Why does safety-critical C++ firmware forbid heap allocation after start-up, and which standard C++ features allocate without saying so?

level: juniorimportance: must knowfreq 60%

basics

~10 s

Heap allocation can fail or fragment at an unpredictable moment and takes unbounded time, which a pacemaker cannot tolerate. Growing containers, std::string, std::function, std::make_shared and node-based containers can all allocate implicitly.

open as a page

Why can a C++ volatile counter incremented by a UART interrupt handler and decremented by the main loop still lose updates?

level: middleimportance: must knowfreq 60%

basics

~20 s

Incrementing a volatile counter is still a separate load, add and store. If the interrupt fires between the main loop's load and store, one update is overwritten. Use a lock-free std::atomic or mask the interrupt around the update.

open as a page

When a C++ codebase is built with exceptions disabled, what happens to throw and try, and how do functions report failure instead?

level: juniorimportance: should knowfreq 55%

basics

~10 s

Code that writes throw, try or catch no longer compiles. Functions return the failure instead: an error enum or std::error_code, std::optional, or C++23 std::expected, and constructors that can fail become factory functions.

open as a page

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%

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.

open as a page

In a C++ build with exceptions disabled, what does std::vector::at do with an out-of-range index, and why does that depend on the library?

level: middleimportance: should knowfreq 45%

basics

~20 s

The standard only says at throws std::out_of_range; with exceptions off, each library decides. libc++ ends the program through its abort path, and libstdc++ calls a helper compiled into its library, which normally throws, so std::terminate follows.

open as a page

In C++, what puts a lookup table in read-only memory, and which declarations silently move it to RAM or rebuild it at start-up?

level: middleimportance: should knowfreq 50%

basics

~20 s

A constexpr table at namespace scope, or a static constexpr local, is constant-initialized and const, so toolchains put it in a read-only section kept in flash. constinit tables stay in RAM; const tables with runtime initializers are built at start-up.

open as a page

Without a heap, why is std::array plus a count a weak fixed-capacity container in C++, and what does C++26 std::inplace_vector change?

level: middleimportance: should knowfreq 35%

basics

~20 s

std::array constructs all N elements up front, so the type needs a default constructor and unused slots hold live objects. C++26 std::inplace_vector constructs elements only on insertion, and try_push_back reports a full container without throwing.

open as a page

How should a C++ UART receive interrupt hand bytes to the main loop, and why do the buffer indices need std::atomic with release and acquire rather than volatile?

level: seniorimportance: should knowfreq 45%

basics

~20 s

Use a single-producer, single-consumer ring buffer: the handler writes the byte, then stores the head index with release; the main loop loads head with acquire before reading the slot. volatile indices give no ordering for the plain buffer writes.

open as a page

Which volatile operations did C++20 deprecate and C++23 restore, and is reg |= TX_ENABLE on a volatile register still deprecated?

level: seniorimportance: should knowfreq 35%

basics

~20 s

No. C++20 deprecated ++, --, compound assignment, using an assignment's result, and volatile parameters, returns and structured bindings. Defect reports for C++23 restored compound assignment, so reg |= TX_ENABLE as a statement is fine; ++reg stays deprecated.

open as a page

How do you construct a C++ object in a static buffer with placement new, and which alignment and lifetime rules must the firmware follow?

level: seniorimportance: should knowfreq 40%

basics

~10 s

Reserve alignas(T) std::byte storage[sizeof(T)] with static storage duration, construct with ::new (static_cast<void*>(storage)) T(args), use the pointer new returned, and end the object with std::destroy_at before the storage is reused or reconstructed.

open as a page

As the lead of a motor-controller firmware or a console game engine in C++, how do you decide whether to disable exceptions and RTTI, and what must the team standardise if you do?

level: principalimportance: should knowfreq 40%

basics

~20 s

Disable them when image size, worst-case timing or certification evidence outweigh the cost of hand-written error paths and of libraries that assume exceptions; then standardise one error type, the fatal-error handler, the banned library calls and the enforcement.

open as a page

In a C++ game engine built with RTTI disabled, which standard library members stop compiling or quietly change behaviour, and do libc++ and libstdc++ agree?

level: seniorimportance: nice to knowfreq 25%

basics

~10 s

Members that answer with a std::type_info vanish: std::any::type and std::function::target_type. libc++ also drops std::function::target and std::get_deleter, while libstdc++ keeps them and get_deleter silently returns null. std::any_cast keeps working.

open as a page

What must a freestanding C++ implementation provide, and how did C++23 and C++26 widen the freestanding standard library?

level: seniorimportance: nice to knowfreq 25%

basics

~20 s

A freestanding implementation must supply at least a listed set of headers and their freestanding items; whether main is required is implementation-defined. The C++23 list has 26 headers, including utility, memory and ranges; C++26 lists 48, adding array, optional and inplace_vector.

open as a page