volatile
Whereas the qualifier const tells
the compiler “This never changes” (which allows the compiler to
perform extra optimizations), the qualifier
volatile tells the compiler “You never know
when this will change,” and prevents the compiler from performing any
optimizations based on the stability of that variable. Use this keyword when you
read some value outside the control of your code, such as a register in a piece
of communication hardware. A volatile variable is always read whenever
its value is required, even if it was just read the line
before.
A special case of some storage being
“outside the control of your code” is in a multithreaded program. If
you’re watching a particular flag that is modified by another thread or
process, that flag should be volatile so the compiler doesn’t make
the assumption that it can optimize away multiple reads of the
flag.
Note that volatile may have no
effect when a compiler is not optimizing, but may prevent critical bugs when you
start optimizing the code (which is when the compiler will begin looking for
redundant reads).
The const and volatile
keywords will be further illuminated in a later
chapter.