volatile
Go Up to Keywords, Alphabetical Listing Index
Category
Syntax
volatile <data definition> ;
Description
Use the volatile modifier to indicate that a background routine, an interrupt routine, or an I/O port can change a variable. Declaring an object to be volatile warns the compiler not to make assumptions concerning the value of the object while evaluating expressions in which it occurs because the value could change at any moment. It also prevents the compiler from making the variable a register variable.
volatile int ticks; void timer( ) { ticks++; } void wait (int interval) { ticks = 0; while (ticks < interval); // Do nothing }
The routines in this example (assuming timer has been properly associated with a hardware clock interrupt) implement a timed wait of ticks specified by the argument interval. A highly optimizing compiler might not load the value of ticks inside the test of the while loop since the loop does not change the value of ticks.
Note: C++ extends volatile to include classes and member functions. If you have declared a volatile object, you can use only its volatile member functions.