Volatile Variables – What Does Declaring One Mean?

clow-level

Many low level programs use the volatile keyword for types for memory mapping and such, however I'm sort of confused as to what it REALLY does in the background. In other words, what does it mean when the compiler doesn't "optimize away" the memory address?

Best Answer

volatile means some other processor or I/O device or something can change the variable out from under you.

With an ordinary variable, your program's steps are the only thing that will change it. So for instance if you read 5 from a variable and you don't change it, it'll still contain 5. Since you can rely on that, your program doesn't have to take the time to read the variable again next time you want to use it. The C++ compiler is smart to generate code that just remembers the 5.

But you could read it as 5, then perhaps the system loads data from disk into that memory, changing it to 500. If you want your program to read the fresh value 500, you need the compiler to not be too smart about using the previously-read 5. You need to tell it to reload the value every time. That's what volatile does.

An analogy for 5-year olds
Let's say you put a big sheet of paper on a table. In one corner of the paper, you write down the current score of an ongoing game, 3 to 4. Then you go to the opposite side of the table and start writing a story about the game. Your friend who's watching the game updates the score in that corner as the game proceeds. She erases 3 to 4 and writes 3 to 5.

When you go to put the game score into your story, you could either:

  1. Write down the last score you read, 3 to 4, merrily assuming it didn't change (or not minding if it did), or
  2. Walk around to the opposite side of the table to read the current score (which happens to be 3 to 5 now), and walk back. That's how a volatile variable acts.
Related Topic