volatile
keyword (C)
The volatile keyword in C tells the compiler that a variable’s value may change unexpectedly, typically due to external factors.
Usage
Prevents Optimization: It prevents the compiler from optimizing out what it may see as unnecessary reads or writes to the variable.
Common Uses: Used in embedded systems, for hardware access, and in multithreading environments.
A Hint to the Compiler, Not the Hardware
The volatile keyword is a directive to the compiler, not to the underlying hardware. It does not affect how the hardware interacts with memory; rather, it affects how the compiler generates code around accesses to the volatile variable.
Try this demo
/usr/bin/arm-none-eabi-gcc -S -fverbose-asm -I /usr/include/ \
-c volreg.c -o /dev/stdout
Notice how the compiler does not load variable b again when it adds 1 to it.
Let’s see how the program behaves when we turn on optimization:
/usr/bin/arm-none-eabi-gcc -S -fverbose-asm -I /usr/include/ \
-c volreg.c -o /dev/stdout -O
With optimizations turned on, the compiler removes any code that is inconse-
quential or can be precomputed. But not for volatile variables