{ foo = 0; while (foo != 255) ; } An optimizing compiler will notice that no other code can possibly change the value stored in foo, and will assume that it will remain equal to 0 at all times. The compiler will therefore replace the function body with an infinite loop similar to this: void bar_optimized(void) { foo = 0; while (true) ; } However, foo might represent a location that can be changed by other elements of the computer system at any time, such as a hardware register of a device connected to the CPU. The above code would never detect such a change; without the volatile keyword, the compiler assumes that the current program is the only part of the system that could change the value (which is by far the most common situation). To prevent the compiler from optimizing code as above, the volatile keyword is used: static volatile int foo; void bar (void) { foo = 0; while (foo != 255) ; } With this modification the loop condition will not be optimized away, and the system will detect the change when it occurs. Generally, there are memory barrier operations available on platforms (which are exposed in C++11) that should be preferred instead of volatile as they allow the compiler to perform better optimization and more importantly they guarantee correct behaviour in multi-threaded scenarios; neither the C specification (before C11) nor the C++ specification (before C++11) specifies a multi-threaded memory model, so volatile may not behave deterministically across OSes/compilers/CPUs. Optimization comparison in C The following C programs, and accompanying assemblies, demonstrate how the volatile keyword affects the compiler's output. The compiler in this case was GCC. While observing the assembly code, it is clearly visible that the code generated with volatile objects is more verbose, making it longer so the nature of volatile objects can be fulfilled. The volatile keyword prevents the compiler from performing optimization on code involving volatile objects, thus ensuring that each volatile variable assignment and read has a corresponding memory access. Without the volatile keyword, the compiler knows a variable does not need to be reread from memory at each use, because there should not be any writes to its memory location from any other thread or process. C++11 According to the C++11 ISO Standard, the volatile keyword is only meant for use for hardware access; do not use it for