Thursday, February 9, 2012

What are volatile variables ?

The volatile keyword acts as a DATA TYPE QUALIFIER . It alters the default way in which the compiler handles the variable and does not attempt to optimize the storage referenced by it.

volatile means the sorage is likely to change anytime by code outside the control of the user program. This means that if you reference a variable, the rogram should always read from the physical address and not its cached value.

A volatile keyword is an instruction to the optimizer to make sure that the variable or function is not optimized during compilation.

eg :
         
...
...
int flag=1;
while(flag);
...
...

Here , on compilation the compiler assumes that the value of the flag won't be changed during  the execution of the program. So the compiler is free to ignore the while(flag) loop instructions during optimization. However, if the flag variable is changed outside this program control ( say by an interrrupt routine or by some other thread) then it is advisable to declare the flag as a volatile variable.


No comments:

Post a Comment