volatile is a rarely-used and little understood keyword in the C programming language. Here is my best information on what exactly it means.

When you tell the compiler that you want a variable to be volatile, this basically tells it to not do any really fancy optimisations. This means that the compiler has to make sure that at the end of every statement, all side-effects pertaining to volatile memory have be in effect. The best example that comes to mind is this:

int my_int;
my_int = 5;
...
/* Some more statements */
...
my_int++;

What is the state of my_int's actual memory between my_int = 5 and my_int++? Well, since we haven't declared my_int as a volatile, this is undefined. The compiler may just put my_int into a register and then operate on that, and only after my_int++ will it update the memory value. All references to my_int would just refer to the register.

If we instead say

volatile int my_int;
my_int = 5;
...
/* Some more statements */
...
my_int++;
then between my_int = 5 and my_int++ we know that the memory for my_int is equal to 5.

Usually this is no big deal to the programmer. The compiler can do whatever it wants in the machine language as long as in the end, it performs correctly. However, there are certain times when you want to make sure that the memory is accurate between statements.

  • Shared memory. You have a piece of code that changes some memory shared between two different processes. You want to make sure that the memory really is updated by the time the other process reads it.
  • Memory mapping. This is a form of shared memory. It is alright to optimise your memory accesses while the file is open, but when you unmap the file you really want to make sure that all your changes are properly recorded.
  • Threaded programming. In most threaded programs, there will be some communication between processes. This is usually through the memory that the threads share together, since it is a fast method. See above for why shared memory often needs volatile.