What is volatile and when must you use it?
Short answer: volatile tells the compiler that a variable can change, or that accessing it has side effects, in ways the compiler cannot see in the code. The compiler must then perform every read and write that appears in the source, in program order relative to other volatile accesses, and may not cache the value in a register, merge accesses or delete them.
Use it for
- Memory-mapped peripheral registers (status registers change by themselves; writing a data register sends a byte).
- Variables shared between an ISR and the main code (flags, indexes of a ring buffer).
- Memory written by DMA or by another core/bus master, when the CPU polls it.
- Local variables modified between
setjmpandlongjmp. - Variables you want to observe or change from a debugger while code runs (e.g. a test loop counter).
static volatile bool g_rx_ready; /* set in the ISR */
void USART2_IRQHandler(void)
{
(void)USART2->DR; /* read clears the flag */
g_rx_ready = true;
}
int main(void)
{
while (!g_rx_ready) { } /* without volatile, -O2 may read once and loop forever */
}
What goes wrong without it: the optimiser sees that nothing inside the loop changes g_rx_ready, loads it once, and turns the loop into if (!g_rx_ready) for (;;);. Similarly, writes to a register in a sequence (CTRL = 1; CTRL = 0;) may be merged into only the last write.
What volatile does not do: it does not make count++ atomic, does not make 64-bit accesses atomic on a 32-bit CPU, and does not insert CPU memory barriers. See the next question.
Cost: volatile accesses cannot be optimised, so mark only what needs it; copy a volatile into a local variable when you use it several times in one calculation.