What does volatile mean in C++ and what changed in C++20?
Short answer: As in C, volatile tells the compiler that every read and write of the object is an observable side effect (e.g. a hardware register), so it must not optimise accesses away, merge them, or reorder them relative to other volatile accesses. It does not make operations atomic and does not provide memory ordering for multi-threaded code — use std::atomic for that. C++20 deprecated compound operations on volatile objects (++, --, +=, |= ...), volatile function parameters and return types, because they suggest an atomic read-modify-write that does not exist; write explicit loads and stores instead.
#include <cstdint>
struct GpioRegs { volatile uint32_t ODR; volatile uint32_t BSRR; };
void toggle(GpioRegs *gpio, uint32_t pin_mask)
{
// gpio->ODR ^= pin_mask; // deprecated in C++20: hides a read-modify-write
uint32_t v = gpio->ODR; // explicit read
gpio->ODR = v ^ pin_mask; // explicit write (still not atomic w.r.t. interrupts)
}
void set_atomic(GpioRegs *gpio, uint32_t pin_mask)
{
gpio->BSRR = pin_mask; // hardware set/reset register: a single write, no RMW race
}
C++23 note: after feedback from the embedded community, C++23 un-deprecated the bitwise compound assignments (|=, &=, ^=) on volatile, because they are so common in register code; ++, --, += and the other cases remain deprecated.
volatile vs atomic
volatile |
std::atomic<T> |
|
|---|---|---|
| Prevents optimising accesses away | yes | yes (for the atomic object) |
| Atomic read-modify-write | no | yes (fetch_add, compare_exchange) |
| Memory ordering with other variables | no | yes (memory_order_*) |
| Use for | MMIO registers, variables changed by hardware | data shared between threads/ISRs |
Embedded rule: registers → volatile; flags shared between an ISR and the main loop on a single-core MCU → std::atomic (lock-free for word sizes on Cortex-M3+; on Cortex-M0 check is_lock_free()) or volatile plus a critical section for multi-step updates.