Wednesday, September 1, 2010

Volatile in C

When you declare a variable as a volatile, then you are telling the compiler that this variable may be changed by some external factor and do not optimize the code related to this variable.
Example:
int foo=0;
while (foo != 10)
//do sth

if this code is optimized, the compiler will make the loop always true because it seems it would not be changed through the code (while (true)).

Cases you need to declare a variable as Volatile:
  • Memory-mapped peripheral registers
  • Global variables modified by an interrupt service routine
  • Global variables accessed by multiple tasks within a multi-threaded application
More info at http://www.netrino.com/node/80

No comments: