Sunday, July 27, 2008

volatile - tell the compiler not to optimize!

Let's re-visit the code used in my previous post:

void foo()
{
    const int i = 0;
    int *j = (int *) &i;
    *j = 1;
    printf("%d\n", i); // prints 0
    printf("%d\n", *j); // prints 1
}

Remember, the compiler doesn't expect the code to modify a const? However, we can give it a "hint" that the const can still get modified (by your own code if the const is local or by an external source) and ask the compiler not to optimize the usage of the const (by replacing it with its value wherever it is used).

volatile is the keyword that forces the compiler to not optimize the usage of the const. Now, note the output of the following code:

void foo()
{
    volatile const int i = 0;
    int *j = (int *) &i;
    *j = 1;
    printf("%d\n", i); // prints 1
    printf("%d\n", *j); // prints 1
}

Also, note that usage of volatile alongside const doesn't mean that the compiler will allow an int pointer to point to a const int without a typecast. In other words, the typecast in the following statement is still required and not using it will cause a compiler error:
int *j = (int *) &i;

To summarize, the volatile keyword will cause the compiler to shed any optimizations with the usage of the variable and generates code to fetch the value from the associated memory location everytime the code refers to the variable.

No comments: