9.8.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 INTCON1 __attribute__((__sfr__));

The code produced by the compiler to access volatile objects may be different to 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. Failure to use this qualifier when it is required, may lead to code failure.

Another use of the volatile keyword is to prevent variables being removed if they are not used in the 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 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 the 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.

Some variables are treated as being volatile even though they may not be qualified in the source code. See 17 Mixing C and Assembly Code if you have assembly code in your project.