skip to content

Registers and Volatile

volatile stops the compiler eliding reads and writes to a memory-mapped register but gives no atomicity or ordering. Interviewers ask volatile versus std::atomic.

on this pageshow

explore

questions

5

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 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

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

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