Volatile is a type qualifier that tells the complier the value of varible will change at any time, modified by multiple processes other than the present program. Based on this information, the compiler may refrain from optimizing access to the variable.
Sample code:
int foo;
void bar(void) {
foo = 0;
while (foo != 255)
;
}
If compile it with optimization option, the complier will notice that no other code can possibly change the value stored in foo, and will assume that it will remain equal to 0 at all times. The compiler will therefore replace the function body like this:
void bar_optimized(void) {
foo = 0;
while (true);
}
However,foo might represent a location that can be changed by other elements of the computer system at any time. The above code will have problem. Whithout volatile, the compiler assumes that only the current program change foo’s value. So add volatile prevent complie to do optimize on foo.
A variable should be declared volatile whenever its value could change unexpectedly. In practice, only three types of variables could change:
1. Memory-mapped peripheral registers
2. Global variables modified by an interrupt service routine
3. Global variables accessed by multiple tasks within a multi-threaded application
Reference:
http://en.wikipedia.org/wiki/Volatile_variable
How to use C’s volatile keyword