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.

3 comments:

Anonymous said...

I am not a programmer but believe me you, your articles are so good for getting to understand things and how they work.. I will stay tuned here and hoping to learn more..

Joshua said...

Thanks oneminutevcc.tk for the wonderful comment. i will keep sharing my experiences.

Joshua said...

Hi Christi Parks, the scope for c programming is rather wide. but most of the available online books will try to cover the most important topics. for example http://www.ee.kntu.ac.ir/computer/En/Research/Areas/Files/Introduction%20to%20the%20C%20Programming%20Language/book.pdf

Any good book you pick will almost cover similar content.
My advise to you is; Choose one good book, read it cover to cover while doing the exercises and examples (you will need access to a good c compiler and builder; try Borland c compiler).

Then, depending on the type of project you wish to accomplish, you can always come back to some material and dive deeper to get expert knowledge. myself, am not a c expert by some times i land on projects that require me to use c. for example this year am doing embedded systems programming in c.

Good luck.