Please note as of Wednesday, August 15th, 2018 this wiki has been set to read only. If you are a TI Employee and require Edit ability please contact x0211426 from the company directory.

Volatile

From Texas Instruments Wiki
Jump to: navigation, search

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.

The C standard

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

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

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

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.