Volatile in C
In C, the volatile keyword indicates that a value may change between different accesses, even if it does not appear to be modified.
The volatile
keyword prevents the compiler from performing optimization on code involving volatile objects, thus ensuring that each volatile variable assignment and read has a corresponding memory access(Wikipedia reference).
It is intended to prevent the compiler from applying any optimizations on objects that can change in ways that cannot be determined by the compiler.
For example a global variable can represent a data port (usually global pointer referred as memory mapped IO) which will be updated dynamically. The code reading data port must be declared as volatile in order to fetch latest data available at the port..
Below is a demo which shows how the compiler will behave when there is volatile
or not
Obviously without volatile the four variable was optimized by the compiler so they are not shown in the assembly code, but with volatile keyword, the four variable was not optimized so everyone has a location in memory stack.
Last updated