In computer programming, a variable or object declared with the volatile keyword may be modified externally from the declaring object. For example, a variable that might be concurrently modified by multiple threads (without locks or a similar form of mutual exclusion) should be declared volatile. Variables declared to be volatile will not be optimized by the compiler because their value can change at any time.
What can happen if volatile is not used?
The following piece of C source code demonstrates the use of the volatile keyword.
int foo(void) { int *addr = 100; *addr = 0; while (*addr != 1) ; }
In this example, the code sets the value stored at ___location 100 in the computer system to 0. It then starts to poll the address until it changes to 1.
An optimizing compiler will assume that no other code will change the value stored in ___location 100 and so it will remain equal to 0. It will then replace the while loop with something similar to this: -
int foo(void) { int *addr = 100; *addr = 0; while (1) ; }
and the program will loop forever.
However, the address might represent a ___location that can be changed by other elements of the computer system. For example, it could be a hardware register of a device attached to the CPU with a bus. The value stored there could change at any time. The above code would never detect the change.
To prevent the compiler from modifying code in this way, the volatile keyword is used in the following manner: -
int foo(void) { volatile int *addr = 100; *addr = 0; while (*addr != 1) ; }