Thread: Volatile Keyword!!

  1. #1
    Registered User
    Join Date
    Dec 2005
    Posts
    136

    Question Volatile Keyword!!

    Hello....

    Could any one tell me what is Volatile Keyword in C programming, Why and where we need to use a volatile variable in our program. How compiler manage this type of variable

  2. #2
    Sr. Software Engineer filker0's Avatar
    Join Date
    Sep 2005
    Location
    West Virginia
    Posts
    235

    Variable Volatility

    The volatile keyword tells the compiler that the value of the variable may change at any time, so it can't optimize in such a way that repeated references to the value of the variable don't access the actual variable's storage for each reference (common subexpression reduction, moving the value to a register, and other common optimizations do this). It is generally used on objects (variables) that are shared between threads or programs, changed by signal handlers, or in device registers.

    Without the volatile keyword, the compiler is free to convert expressions like:
    Code:
    a = c + c + c;
    into
    Code:
    a = 3 * c;
    This would not give you the correct answer if the variable c was actually a register that incremented each time it was accessed. (This is a contrived example.)

    It's either that, or the variable is very grumpy and likely to get angry and go off the handle for no apparent reason, or maybe it bursts into flame when touched.
    Last edited by filker0; 12-05-2005 at 03:43 PM. Reason: Add details
    Insert obnoxious but pithy remark here

  3. #3
    Registered User
    Join Date
    Dec 2005
    Posts
    136
    Thanks for ur Answer filker0, But my problem hasn't solved yet!!!

    Your words " The volatile keyword tells the compiler that the value of the Variable may change at any time", Isn't it the same as the defination of a normal variable.

    If i declared a variable "int p;" and next i said to incremet the value of "p" 1000 times. then this means variable is changing its value 1000 times,which is said by the programmer explicitly. Right?
    Now as i know about volatile variab is that, compiler is going to change the volatile variable at any moment of time during its execution i.e programmer dont have any control on that variable. Then plz tell me what is the need of that kind of variable whose value is not predictable.
    why a progrramer use this volatile variable in his program, what is the benifit of using this.
    and plz tell me also how does compiler manage this variable(regards to memory allocation and manipulations).

    Please clear more the concepts.
    Thanks.

  4. #4
    Registered User hk_mp5kpdw's Avatar
    Join Date
    Jan 2002
    Location
    Northern Virginia/Washington DC Metropolitan Area
    Posts
    3,817
    If thread A initializes a variable to 100 and then thread B changes it to 1000 then when A accesses the value next, due to possible compiler optimizations, it might assume that the value was still 100 and might not actually go and check for the real value unless the volatile keyword was used. In that case, each and every access of such a variable would go fetch the current real-time value from memory instead of making an assumption as to its value.
    "Owners of dogs will have noticed that, if you provide them with food and water and shelter and affection, they will think you are god. Whereas owners of cats are compelled to realize that, if you provide them with food and water and shelter and affection, they draw the conclusion that they are gods."
    -Christopher Hitchens

  5. #5
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    Here is an illustration:
    Code:
    int foo;
    volatile int bar;
    
    ... read any value you like into 'bar' ...
    
    for( x = 0; x < bar; x++ )
    {
        ...do whatever you like...
    }
    Let's pretend that we entered 10 for bar's value. The compiler can't just take 10 and insert it where bar is, because we have told the compiler that it's possible bar's value will change.

    Without the keyword, it's possible the code would be instead changed to:
    Code:
    for( x = 0; x < 10; x++ )
    It's likely this wouldn't happen. But it could. For example, commonly people frown on this:
    Code:
    for( x = 0; x < strlen( mystring ); x++ )
    Citing that it's unwise to keep calling the strlen function every time through the loop. However, this may not be the case. It's possible that given an unchanging mystring, the code 'x < strlen( mystring )' be changed to instead be 'x < N', where N is the length of the string, and not the return value of the function strlen.




    Quzah.
    Hope is the first step on the road to disappointment.

  6. #6
    Sr. Software Engineer filker0's Avatar
    Join Date
    Sep 2005
    Location
    West Virginia
    Posts
    235
    hk_mp5pdw has it right. Your objection that a variable is intended to vary is a different thing than being volatile. The compiler knows when it's changing a variable. It also knows that any non-local or aliased variable may change when it calls a function.

    A common use of volatile in modern C code is with pointers to locations. In the example
    Code:
    volatile unsigned long * sysclock = (unsigned long *)SYSCLOCK;
    unsigned long then;
    unsigned long now;
    int i;
    
    then = *sysclock;
    for (i = 0; i < 10000; ++i)
    {
        // do nothing in the loop -- just see how long it takes to do 10000 iterations
    }
    now = *sysclock;
    printf("the loop took %uld clock cycles\n", now - then);
    the compiler wouldn't know that the value pointed to by sysclock might change, since no function calls are being made, between the reading of its value into the variable "then" and the later reading of its value into the variable "now" without the volatile keyword. The code that the compiler sees certainly never changes it. Not all compilers will optimize this sort of thing, but many will.

    This is, of course, still a contrived example. You might want to look at http://msdn.microsoft.com/library/de...tm/ators_6.asp and/or http://www.programmersheaven.com/art...k/article1.htm for a detailed description of volatile.

    I used to write C compilers for a living, and these days I write device drivers, real-time and embedded code. volatile is an essential tool.
    Last edited by filker0; 12-05-2005 at 04:30 PM. Reason: Add another reference
    Insert obnoxious but pithy remark here

  7. #7
    Gawking at stupidity
    Join Date
    Jul 2004
    Location
    Oregon, USA
    Posts
    3,218
    Things like signals are interrupt-driven. Let's say you have your loop that changes a variable 1000 times in it. Without optomization your program would grab the memory that the variable uses, place it in a CPU register, make the change, and put the new value back to the variable's memory location.

    With optomization the compiler might say "Hey! Why am I doing so may reads and writes to the same memory location if that's all I'm doing?" and will just keep that variable in a CPU register instead of touching RAM every time. This works great most of the time, but let's say you had a signal handler that had to change a global variable. And let's say that same global variable was used in your loop.

    Now, what if your loop was through 500 iterations and then the signal was triggered? Your signal handler would change the variable, but the loop wouldn't see the change because it's using its privately stored copy of the variable instead of the value from RAM. Using 'volatile' tells the compiler not to do that kind of optomization with that variable to avoid such disasters.
    If you understand what you're doing, you're not learning anything.

  8. #8
    Sr. Software Engineer filker0's Avatar
    Join Date
    Sep 2005
    Location
    West Virginia
    Posts
    235

    Another reference

    Another decent web page dedicated to volatile is here .
    Insert obnoxious but pithy remark here

  9. #9
    Registered User
    Join Date
    Dec 2005
    Posts
    136

    Thumbs up

    Thanks A lot buddy,
    Ur posts and link r really helpful.
    S_ccess is waiting for u. Go Ahead, put u there.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Multithreading (flag stopping a thread, ring buffer) volatile
    By ShwangShwing in forum C Programming
    Replies: 3
    Last Post: 05-19-2009, 07:27 AM
  2. Replies: 16
    Last Post: 10-29-2006, 05:04 AM
  3. Virtual Keyword
    By Shal in forum C++ Programming
    Replies: 6
    Last Post: 05-18-2006, 11:37 AM
  4. volatile keyword help!!!!
    By penney in forum Linux Programming
    Replies: 2
    Last Post: 03-12-2003, 08:09 AM
  5. how to search a keyword in C?
    By kreyes in forum C Programming
    Replies: 2
    Last Post: 03-01-2002, 08:22 PM