Technical Note

: SLE00010

Author

: Scott Evans

Created/Modified

: 6/10/99

Description

: The volatile keyword 

This technical note describes the volatile keyword used in C and C++. If the volatile keyword is used when declaring a variable it warns the compiler that an external process can change the variable. These types of variables are not subject to compiler optimisations. The compiler will always produce code to write a volatile variable straight away and read it each time it is referenced.

For example say we had some hardware that set a register while it was busy and cleared the register when it had finished its processing. Now you code some software that needs to wait for the hardware to finish processing. It might look like this.

// Address of hardware busy register

unsigned long *const busy=(unsigned long *)0x8001000;

while(*busy)

{

// Wait for hardware to clear register

}

Now chances are this will work, but in certain circumstances when the compiler has been optimising the value of *busy might not be updated. This could cause the software to get stuck in an infinite loop.

The way to be sure that this never happens is to declare the busy variable as volatile.

// Address of hardware busy register

volatile unsigned long *const busy=(unsigned long *)0x8001000;

while(*busy)

{

// Wait for hardware to clear register

}

The above bit of code will always produce the desired result since the compiler is forced to always read the value of *busy when it is referenced.


This document in word format.
This document in text format.