What is volatile (type qualifier)?
A C type qualifier that tells the compiler that a variable's value may change outside the program's view (by a peripheral, an interrupt handler and so on), or that the accesses themselves matter. Accesses to a volatile object are not removed or merged; they are performed as many times and in the order written. It is used for memory-mapped I/O registers and for flags shared with interrupt handlers. It does not make operations atomic or guarantee ordering with respect to other cores.
Japanese name: volatile(型修飾子)
volatile (type qualifier) appears in 7 practice questions across 6 topics, including C Programming Basics, OS & Hardware, Multicore & Synchronization.
Field: C Programming Basics
What volatile does not do
volatile does not make a read-modify-write operation atomic, so an interrupt in the middle of *reg |= mask; can make another bit's change disappear. A value too wide to be read or written at once, such as a 32-bit variable on an 8-bit microcontroller, can be read half-updated if an interrupt occurs in between. For synchronization between threads, mechanisms that guarantee atomicity and ordering, such as C11 _Atomic or locks, are used.
FAQ
Can const and volatile be used together?
Yes. const volatile means "the program does not modify it, but it changes for outside reasons, so read it again every time", and is used for read-only status registers and the like.
Does volatile make code slower?
For that variable, the optimization of keeping its value in a register is no longer possible, so accesses increase and the code can become slower. For that reason it is applied only where needed, such as peripheral registers and variables shared with interrupt handlers, rather than to every variable.