Volatile variables are declared with the volatile keyword before it. Compiler compiles these variables keeping in mind that they can be altered from other modules like OS/system drivers/hardwares. Thus the compiler never optimizes volatile variables even if we put optimization levels in compilation.
Suppose key press status register is a memory mapped register. In normal situations when no key is pressed, the status register value is zero or cleared. Now, on each key press it becomes non zero and the value of this register is the scan code of the key which has been pressed.
Here we have taken a pointer variable 'key_press' and it points to this status register. Following is a program that displays a message and waits for the user to press any key before it exits.
volatile int *key_press = KEY_PRESS_STATUS_MMAP_REGISTER;
int main(int argc, char *argv)
printf("press any key to exit\n");
*key_press = FALSE; /*Clear previous key press*/
while(*key_press == FALSE)
*key_press = FALSE;
printf("key pressed, exiting\n");
In the above example, if by mistake we forget to put volatile keyword and compile it with optimization the while loop will be as given below:
As the value of 'key_press' is zero, the condition is always true from the optimized perspective. It will become an infinite loop and execution will never terminate.
Putting a volatile keyword before the definition of 'key_press' prevents the optimizer from optimizing the loop condition. Thus it will always check the register and result will be as expected.
You have viewed 1 page out of 248. Your C learning is 0.00% complete. Login to check your learning progress.