</>EmbeddedInterview

What is the volatile keyword?

EasyC Programming

Short answer: volatile tells the compiler that an object can change, or that accessing it has effects, outside the normal flow of the program it can see (hardware, an ISR, another core, a debugger). So every read and write written in the source must actually be performed, in program order relative to other volatile accesses, and cannot be cached in a register, merged or removed.

Three classic cases where it is required

  1. Memory-mapped hardware registers: the value changes on its own (status registers), and writes have effects (sending a byte).
  2. Variables shared with an interrupt handler: the main loop must re-read a flag that the ISR sets.
  3. Variables modified by another thread or core in bare-metal code without an OS (although proper synchronisation is still needed; see below).
static volatile bool data_ready;           /* set in the ISR */

void USART1_IRQHandler(void) { data_ready = true; }

int main(void)
{
    while (!data_ready) { }   /* without volatile, the compiler may read once and loop forever */
    /* ... */
}

What volatile does not do

  • It does not make operations atomic: volatile uint32_t count; count++; is still load–add–store and can lose updates.
  • It does not order non-volatile accesses around it, and it does not add CPU memory barriers (on multi-core systems or with DMA you need __DMB()/atomic_thread_fence() as well).
  • It is not a replacement for mutexes or atomics in multi-threaded code (C11 _Atomic is the right tool there).

Cost: every access goes to memory, which prevents optimisations. Only mark what needs it.

The Embedded C topic covers volatile in more depth, including pointer declarations and the C++20 changes.