The volatile keyword in C tells the compiler that a variable can be changed outside of our code. This prevents the compiler to do optimizations like caching or compile time code optimizations.
One common usage is in embedded systems, when some hardware is mapped into the RAM. Then we have a variable to access some property of that hardware. If some state in that hardware changes, the value of our variable will also change.
Now, if that variable was stored for fast access in the CPU register, then we will not get the updated value from the hardware. This is a classical case to use the volatile keyword.
struct DeviceState { int flag; int ready; int statusCode; }; volatile struct DeviceState device; // You want the entire struct variable to be volatile
Other situation is in multi-threaded code. If our data is not concurrency protected, the value of our variable could change out of our control.
Once again, we want to read the value of this variable from the RAM every time we work with it. Otherwise our program could crash, not work properly or CPU knows what.
Let's say that we are using signal handlers. If we organize an infinite loop, that is interrupted by signal handler, we must define the signal handler as volatile. Otherwise the compiler could try to ‘optimize’ our code and create a true infinite loop. Not cool :-(
volatile int handler = 0; while (!handler) { // You don't want this loop to be optimized to while(1) }
Did you learn what does the volatile
keyword in C mean? I think so. You will use it to tell the compiler that a
variable will be changed outside of our code. Then the compiler will know not
to be too smart with optimizations and always read the value of the variable
from the memory.