Search topics...
C / C++ ConceptsKeywords: volatile, const, staticfoundational

What does the keyword volatile mean? Give three examples of its use.

0 upvotes
Practice with AISoon

volatile tells the compiler that a variable's value may change at any time without any action being taken by the surrounding code. The compiler must reload the variable from memory on every access — it cannot cache it in a register, reorder accesses around it, or eliminate reads that appear redundant.

Three mandatory use cases in embedded systems:

  • Hardware registers — a status register can change between reads because the peripheral updates it independently of the CPU.
  • Variables modified inside an ISR — the main loop reads a flag that an interrupt handler sets; without volatile, the compiler may optimize the re-read into a single load before the loop and never check again.
  • Variables shared between RTOS tasks — multiple threads can modify the same variable concurrently (though volatile alone does not make access atomic — you still need a mutex or critical section).

Failure to use volatile causes bugs that only appear at certain optimization levels — code works in debug (-O0) but breaks in release (-O2).

Source: C / C++ Concepts Q&A