volatile is one of the most important keywords in embedded C, and one of the most misunderstood. Leave it out where it’s needed and your firmware works in a debug build but hangs once optimization is switched on. Add it everywhere “just in case” and your code gets slower without actually becoming correct. This guide covers what volatile really does, the situations where you need it, and the problems it does not solve.
What volatile tells the compiler
Normally a C compiler is free to optimize memory accesses however it likes, as long as the program’s visible behavior stays the same. It can keep a variable in a register instead of rereading memory, merge repeated writes, or delete reads whose results seem unused.
Declaring an object volatile tells the compiler that accessing it is a side effect in itself. In practice that means:
- Every read in your source code becomes a real read from memory, and every write becomes a real write.
- Accesses aren’t cached in registers, merged or removed.
- Volatile accesses stay in program order relative to other volatile accesses.
The compiler has to assume the value can change at any moment for reasons it can’t see (hardware, an interrupt, a DMA controller), and that writing it may cause something to happen.
The bug volatile prevents
Here’s a classic case. An interrupt sets a flag, and main() waits for it:
#include <stdbool.h>
static bool data_ready = false; /* missing volatile */
void USART2_IRQHandler(void)
{
/* ... read the byte ... */
data_ready = true;
}
int main(void)
{
/* ... setup ... */
while (!data_ready) {
/* wait */
}
/* never gets here at -O2 */
}
Nothing inside the while loop changes data_ready, and the compiler doesn’t know that the interrupt handler can run in the middle of the loop. So it may read the flag once and turn the loop into the equivalent of:
if (!data_ready) {
for (;;) { }
}
The program works without optimization and hangs with it. The fix is one word:
static volatile bool data_ready = false;
Now every pass through the loop rereads data_ready from memory.
When to use volatile
Memory-mapped hardware registers
Peripheral registers can change on their own (a status bit gets set when data arrives), and reading or writing them can have side effects (reading a data register may clear a flag). Register access must always go through volatile:
#define GPIOA_IDR (*(volatile uint32_t *)0x40020010u) /* STM32F4 GPIOA input data */
while ((GPIOA_IDR & (1u << 0)) == 0u) {
/* wait for the button on PA0 */
}
Vendor headers already declare their registers volatile, which is one reason to use them rather than writing your own definitions. Our Embedded C programming guide shows the common register-access patterns.
Variables shared with interrupt handlers
Any variable written in an interrupt service routine and read in main code (or the other way round) should be volatile, as in the flag example above. The same applies to ring-buffer indices, tick counters and state shared with ISRs. Our guide to writing an interrupt service routine in C covers patterns for passing data out of ISRs.
Buffers written by DMA
A DMA controller writes to memory without the CPU knowing about it. If code polls a buffer that DMA fills, or a status word that DMA updates, those accesses need to be volatile, or you need a compiler barrier before reading. See the section on caches below, though, because volatile alone isn’t enough on chips with a data cache.
Local variables across setjmp/longjmp
The C standard says that local variables modified between setjmp() and longjmp() have indeterminate values after the jump unless they’re declared volatile. This is rare in firmware, but it does come up in some error-recovery code.
Debug and delay loops
A crude busy-wait loop gets optimized away entirely unless its counter is volatile:
for (volatile uint32_t i = 0; i < 100000u; i++) { }
This works, but the delay depends on the clock speed, compiler and optimization level. A hardware timer is a better choice for anything beyond a quick test.
When volatile is not enough
This is where most real bugs come from. volatile controls whether the compiler emits an access. It doesn’t make operations atomic, and it doesn’t order non-volatile memory.
Read-modify-write is not atomic
volatile uint32_t event_count;
/* main code */
event_count++; /* load, add, store: three steps */
/* ISR */
event_count++;
On most cores, event_count++ compiles to a load, an add and a store. If the ISR fires between the load and the store, one of the increments is lost. The same applies to REG |= BIT on a variable or register that an interrupt also modifies. To make the main-code update safe, briefly disable interrupts around it or use an atomic operation:
uint32_t primask = __get_PRIMASK(); /* CMSIS, Arm Cortex-M */
__disable_irq();
event_count++;
__set_PRIMASK(primask); /* restore previous interrupt state */
Multi-byte values can tear
On an 8-bit AVR, reading a uint16_t takes two separate byte loads. If an ISR updates the value between them, you can get the high byte of the new value and the low byte of the old one. volatile doesn’t prevent this. avr-libc provides a helper:
#include <util/atomic.h>
volatile uint16_t adc_result; /* written in the ADC ISR */
uint16_t read_adc_result(void)
{
uint16_t copy;
ATOMIC_BLOCK(ATOMIC_RESTORESTATE) {
copy = adc_result;
}
return copy;
}
On 32-bit Arm Cortex-M, aligned 8-, 16- and 32-bit loads and stores are single accesses, so this particular problem mostly goes away for those sizes. It remains for 64-bit values and structs.
Ordering with non-volatile data
A common pattern is to fill a buffer and then set a flag:
static uint8_t buf[32]; /* not volatile */
static volatile bool buf_ready;
void producer(void)
{
fill(buf);
buf_ready = true;
}
The compiler must keep volatile accesses in order with each other, but it’s allowed to move the non-volatile writes to buf past the write to buf_ready. A consumer could then see the flag before the data is complete. Options:
- Make the shared data
volatiletoo (simple, but costs performance). - Put a compiler barrier between the two steps. With GCC and Clang,
__asm volatile ("" ::: "memory");stops the compiler from moving memory accesses across that point. - Use C11 atomics with release/acquire ordering (
atomic_store_explicit(&buf_ready, true, memory_order_release)), which handles both compiler and hardware ordering.
On a single-core microcontroller, a compiler barrier is usually enough when both sides are on the same CPU. When another bus master is involved, such as a second core or a DMA controller, you may also need a hardware memory barrier, such as __DMB() on Arm.
RTOS tasks and multiple cores
volatile is not a thread-synchronization tool. To share data between RTOS tasks, use the RTOS’s queues, mutexes or semaphores, or C11 atomics. They provide atomicity and ordering, and the RTOS versions also handle blocking and priority correctly. The same goes for multi-core chips: volatile on its own doesn’t make one core’s writes visible to another in the right order.
Data caches
Some higher-end microcontrollers, such as Arm Cortex-M7 parts, have a data cache. If DMA writes a buffer in RAM while the CPU has stale copies of those addresses in its cache, a volatile read can still return the cached (old) value, because volatile tells the compiler to issue a load, not the cache to fetch fresh data. Fixes include invalidating or cleaning the relevant cache lines around DMA transfers, or placing DMA buffers in a non-cacheable memory region.
Where the qualifier goes
volatile follows the same placement rules as const, and it’s easy to get backwards:
| Declaration | Meaning | Typical use |
|---|---|---|
volatile uint32_t *p |
Pointer to volatile data | Pointing at a hardware register or a shared buffer |
uint32_t *volatile p |
Volatile pointer to ordinary data | A pointer that an ISR may change |
volatile uint32_t *volatile p |
Both | A pointer changed by an ISR that points to volatile data |
const volatile uint32_t *p |
Read-only through this pointer, but may change | A read-only status register |
const volatile isn’t a contradiction. const means your code won’t write it, and volatile means something else might change it.
volatile in peripheral structs
Arm’s CMSIS headers use short macros for register qualifiers. In C, __IO is defined as volatile (read/write), __I as volatile const (read-only), and __O as volatile (write-only, by convention). Newer headers also use __IOM, __IM and __OM for struct members. A peripheral struct looks like this:
typedef struct {
__IO uint32_t SR; /* status register */
__IO uint32_t DR; /* data register */
__IO uint32_t BRR; /* baud rate */
/* ... */
} USART_TypeDef;
Since every member is volatile, every USART2->SR in your code becomes a real bus access.
The cost of overusing volatile
Every volatile access is a real load or store that the compiler can’t optimize. Inside a loop or a busy ISR, that adds up. Two habits help:
- Only mark what actually needs it. A variable used only within main code, or only within one ISR, doesn’t need volatile.
- Read once into a local. When you need a register value several times, copy it once:
uint32_t sr = USART2->SR; /* one read */
if (sr & USART_SR_ORE) { /* overrun */ }
if (sr & USART_SR_RXNE) { /* data */ }
This is also more correct for registers where reading has side effects. Reading the register twice could clear a flag between your two checks.
volatile, const and atomics compared
| Prevents compiler from removing/merging accesses | Makes updates atomic | Orders surrounding non-volatile accesses | |
|---|---|---|---|
volatile |
Yes | No | No |
const |
No (it only forbids writes through that name) | No | No |
C11 _Atomic / <stdatomic.h> |
Yes, for the atomic object | Yes (lock-free on supported sizes) | Yes, depending on the memory order |
| Disabling interrupts | n/a | Yes, on a single core | Acts as a compiler barrier with CMSIS intrinsics |
Support for C11 atomics depends on the core and toolchain. Cortex-M3 and later have exclusive load/store instructions that make lock-free atomics practical. Cortex-M0/M0+ lacks them, so some atomic operations there are either unavailable or implemented by disabling interrupts. Check your compiler’s documentation.
A note for C++
In C++, the meaning of volatile is essentially the same. C++20 deprecated several uses, including ++, -- and compound assignment such as += on volatile variables, because they suggested an atomicity that doesn’t exist. Because embedded code relies so heavily on REG |= BIT, C++23 un-deprecated the bitwise compound assignments (|=, &=, ^=). If you compile firmware as C++20, expect warnings on some register code.
Checklist
- Use
volatilefor hardware registers, ISR-shared variables, and memory changed by DMA. - Don’t expect
volatileto makex++,x |= maskor multi-byte reads atomic. Use a critical section or atomics. - Don’t rely on volatile for ordering non-volatile data. Use a barrier or release/acquire atomics.
- Use RTOS primitives or atomics to share data between tasks.
- On cached MCUs, manage the cache for DMA buffers.
- Read volatile registers once into a local when you need the value more than once.
- If a bug appears only at higher optimization levels, check for a missing
volatile(and for undefined behavior) before blaming the compiler.
When you’re tracking down a suspected missing-volatile bug, stepping through the generated instructions in a debugger is the most direct way to confirm it. Our article on debugging with JTAG, SWD and GDB shows how. The bitwise operations used throughout this article are covered in bit manipulation in embedded C.