Wednesday, June 20, 2012

Volatile Keyword

"volatile" keyword is used when we don't want compiler to optimize our code. Compiler optimization is something when we refer a variable multiple times, compiler optimizes this instruction by single load instruction and then referr to the register for every access (Compiler converts high level language to assembly language).
So if we declare variable with "volatile" keyword, compiler will not optimize its instruction for this particular variable.
For Example - consider below C program:



Now the assembly conversion (run command - "gcc -S filename.c" in terminal - linux)



Now we will see the volatile keyword's real impact - we have just changed our variable's declaration as volatile as shown below:



Now see the assembly conversion below:


In the above program, we could clearly see that every time there is load instruction followed by save instruction in case of volatile. Now fundamentally we are clear about "volatile" keyword.

But we haven't thought about the need of such type of variables. Volatile keyword is useful when we have many threads sharing the same variables so that whenever a thread try to retrieve the value, there will always be a load instruction (to get correct value) and in the same way there will be save instruction as well.
Or when we have shared hardware between drivers or third party, there also volatile variables are used.
---------------------------------------------------------------------------

Now if we declare volatile pointer variable, will it make any sense? think?
We know pointers holds the address of another memory location, so when we try to retrieve the value, it will always get retrieved from the address i.e. you will always retrieve the value from memory addresses. So if you are retrieving value through a pointer variable then it doesn't make any difference whether pointer is volatile or not. So shall never declare pointers as volatile (it doesn't make any difference).



No comments:

Post a Comment