4.3.8.2 Volatile Type Qualifier
The volatile
type qualifier indicates to the compiler
that an object cannot be guaranteed to retain its value between successive accesses. This
information prevents the optimizer from eliminating apparently redundant references to
objects declared volatile
because these references might alter the
behavior of the program.
Any SFR which can be either modified by hardware, or which drives
hardware, is qualified as volatile
and any variables which can be modified
by interrupt routines should use this qualifier as well. For example:
#include <xc.h>
volatile static unsigned int TACTL __at(0x800160);
The volatile
qualifier does not guarantee that any access
will be atomic, which is often not the case, since the 8-bit AVR architecture can typically
access only 1 byte of data per instruction.
The code produced by the compiler to access volatile
objects can be different of 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, however, can lead to
code failure.
A common use of the volatile
keyword is to prevent some
unused variables being removed. If a non-volatile
variable is never used,
or used in a way that has no effect, then it can be removed before code is generated by the
compiler.
A C statement that consists only of a volatile
variable’s
identifier will produce code that reads the variable’s memory location and discards the
result. For example, if PORTB;
is an entire statement, it will produce
assembly code that reads PORTB.