NOTICE: The Processors Wiki will End-of-Life on January 15, 2021. It is recommended to download any files or other content you may need that are hosted on processors.wiki.ti.com. The site is now set to read only.
Volatile
volatile is a standard C keyword. It indicates to the compiler that an object may affect or be affected by the system in ways the compiler cannot know about.
Contents
The C standard[edit]
ISO 9889:1999 section 6.7.3 "Type qualifiers" paragraph 6 says:
An object that has volatile-qualified type may be modified in ways unknown to the implementation or have other unknown side effects. Therefore any expression referring to such an object shall be evaluated strictly according to the rules of the abstract machine [..]
Understanding volatile[edit]
The volatile keyword has several meanings, all of which essentially mean that there is something the compiler cannot know.
The volatile keyword is a hint to the compiler that it should not be overly-clever when trying to optimize expressions involving a particular variable.
The number of volatile reads and writes must be exactly as they appear in the source code; no more and no less, and in the same order. A volatile object may represent a memory-mapped device, for which a read or a write might trigger a side-effect that is not represented in the C code. For example, in the expression "x + x", it may appear to the compiler that it could optimize the expression by reading x only once, but if x is volatile, each read might have a different value, and might trigger changes in the program's state.
If an object is volatile, some other entity might read or write that object at any time.
Easily overlooked properties of volatile[edit]
If an object can be modified by an interrupt function (or any other external agent or side effect such as DMA, peripheral device, interrupt, another thread, etc), that variable must be declared volatile. A common example is a polling loop:
extern volatile int semaphore; while (semaphore == 0) ;
Because semaphore is volatile, the compiler will read it every time through the loop. If semaphore were not volatile, the compiler would turn this into an infinite loop.
If you have a local variable in a function which calls setjmp, you must declare it volatile if it must retain its value when setjmp returns via longjmp. (This is a requirement of the C standard.)
Fields of a volatile struct are considered volatile.
Using volatile to work around compiler bugs[edit]
Using volatile inhibits a wide variety of compiler optimizations, and judicious use may be able to avoid compiler bugs that have no other workaround. However, using volatile can have a drastic negative effect on performance, so volatile should not be used unless it can be shown to be absolutely necessary.