Search My Techie Guy

Thursday, December 6, 2012

Why use the volatile Keyword in C Programming?


A volatile keyword as used in C Programming or C++ is used to to define a variable and to tell the C Compiler NOT to optimize the section or block of code where that variable is used.


take for example the following variable definition:


int age = 100;
while(age == 100)
{
  //execute this code
}


When the compiler looks at the above code, it may be tempted to optimize it to:


while(true){   //execute this code}

And the compiler is justified to do so because the variable "int age = 100;" doesn’t seem to ever change, Instead of the compiler always loading this variable from memory (if it’s not in the register) and comparing it to 100 before running that block of code, it chooses to optimize it and save on processing time.

why use volatile keywords in c-programming?
But what if that variable changes when the compiler has already modified the code (optimized the code)? may be because of an interrupt or some user input? then we would have runtime issues!!!

This is where we need a volatile keyword, to tell the compiler not to touch that piece of code because that variable which the compiler thinks that it never changes! can actually change.
And this is how we would define the variable with a volatile keyword:


volatile int age = 100;

And this would stop the compiler from optimizing the block of code where the variable “age” is present.
Post a Comment