Understanding volatile variables in C
Solution 1
volatile
indicates that the bytes used to store an object may be changed or accessed by something else running in parallel with the program. In practice this is usually a hardware interface, but sometimes it is used to interface with the operating system as well.
Whereas const
indicates that memory is read-only (to your program), volatile
indicates that some other task has write access to it. const volatile
together indicate that an object represents a hardwired input; you might see such a thing in a microcontroller with a memory-mapped sensor.
How this affects your program is that the compiler treats accesses to the memory specially. If you access it twice, the compiler will not cache the first access and give you the same value twice. It will go to the memory hardware and perform two read operations. And when you modify the object, that modification is written immediately and exactly as you specify, with no buffering or reordering optimizations.
Solution 2
volatile
keyword tells the compiler that the variable can be changed (sounds senseless) so you should take care while optimizing. For example consider this-
bool running = true;
while(running) {
//do something
}
The compiler may change while(running)
to while(1)
but if the variable running
is being affected by the code outside the while loop, like in multi-threading, this will create a bug very hard to spot. So the correct thing would be to declare running
as volatile
.
volatile bool running = true;
while(running) {
//do something
}
Sri Harsha Chilakapati
About Me Mobile (Android & iOS) Application Developer & FP Engineer @ApnaTime | Coding Nerd | Wannabe Linguist (Conversational in 4 languages, and can read 6 Abugidas)
Updated on July 25, 2022Comments
-
Sri Harsha Chilakapati almost 2 years
I'm currently learning C in class and I'm having some confusion understanding volatile variables. My textbook defines them as this.
Volatile Variables
The volatile variables are those variables that are changed at any time by other external program or the same program. The syntax is as follows.
volatile int d;
What is exactly the difference between the normal variables and volatile variables? If volatile variables can be changed by external programs, how can I change the value from another external program.
Thanks.