The volatile type qualifier tells the compiler not to optimize a particular variable, regardless of the optimization settings for the compiler. The compiler will generate code to reread the value from memory, every time the variable is accessed (instead of reading the value from a CPU register, where possible). Normally, you'd specify the volatile type if the value of the variable will be changed by another program, or an interrupt, or something else outside your program.
Another situation would be, if you wanted to code a delay/sleep function. Some libraries for embedded systems have no delay function, so you're forced to code your own, something like this:
Code:
#define SCALE 1000
void delay(int seconds) {
int n, max;
max = seconds * SCALE;
for (n = 0; n <= max; n++)
;
}
With optimizations turned on, the compiler may detect that you're not doing anything useful in the for loop. Therefore, it may compile the code, as though you'd written:
Code:
#define SCALE 1000
void delay(int seconds) {
int n, max;
n = seconds * SCALE;
}
This is clearly the wrong thing, since the code does not pause at all! To prevent this from happening, you would write something like this:
Code:
#define SCALE 1000
void delay(int seconds) {
volatile int n, max;
max = seconds * SCALE;
for (n = 0; n <= max; n++)
;
}
The volatile declaration will prevent the compiler from optimizing the code and it will compile the code, exactly the way you intended it to work. Hope this helps!