9.9.2 Volatile Type Qualifier

The volatile type qualifier is used to tell the compiler that an object cannot be guaranteed to retain its value between successive accesses. This prevents the optimizer from eliminating apparently redundant references to objects declared volatile because it may alter the behavior of the program to do so.

Any SFR which can be modified by hardware or which drives hardware is qualified as volatile and any variables which may be modified by interrupt routines should use this qualifier as well. For example:

extern volatile unsigned int WDTCON __attribute__((section("sfrs")));

The volatile qualifier does not guarantee that any access will be atomic, but the compiler will try to implement this.

The code produced by the compiler to access volatile objects may be different than that to access ordinary variables and typically the code will be longer and slower for volatile objects, so only use this qualifier if it is necessary. However, failure to use this qualifier when it is required may lead to code failure.

Another use of the volatile keyword is to prevent variables from being removed if they are not used in the C/C++ source. If a non-volatile variable is never used, or used in a way that has no effect on the program’s function, then it may be removed before code is generated by the compiler.

A C/C++ statement that consists only of a volatile variable’s name will produce code that reads the variable’s memory location and discards the result. For example the entire statement:

PORTB;

will produce assembly code that reads PORTB, but does nothing with this value. This is useful for some peripheral registers that require reading to reset the state of interrupt flags. Normally such a statement is not encoded as it has no effect.