volatile is a type qualifier in C/C++. There are a few important use cases of this, including when we interface with hardware (memory-mapped IO) that changes the value itself (as opposed to within the program). This essentially asks the operating system not to look at the cache for this data, but instead a connected I/O device.

In Nios and ARM, using volatile tells the compiler to use ldwio and stwio instructions instead of ldw and stw.

It tells the compiler not to optimise anything associated with the variable, especially because its value may change outside of the compiler’s detection.

  • For example, successively writing to a pointer would ordinarily be optimised out. However, for a memory-mapped IO device, this can meaningfully change the result of the program.
  • The compiler will also not reorder volatile reads and writes with respect to other volatile ones. Note that this does not give us atomicity for safe inter-thread communication.