Wednesday, September 14, 2011

volatile keyword in C++

I came across the keyword volatile for the first time.

It is used to prevent the compiler from modifying a segment of code for optimization. Variables defined with volatile keyword can be used for:
  • accessing memory mapped devices
  • signal handlers etc.
Here is an example (from wikipedia).

static int foo;
 
void bar(void) {
    foo = 0;
 
    while (foo != 255)
         ;
}
 

This code will be optimized to:
 
void bar_optimized(void) {
    foo = 0;
 
    while (true)
         ;
}
by an optimizing compiler.

If, however, the variable foo can change outside the code, we do not want the compiler to modify it. So, we use the volatile keyword as follows:
 
static volatile int foo;
 
void bar (void) {
    foo = 0;
 
    while (foo != 255)
        ;
}

No comments:

Post a Comment