Thread: VOLATILE vs Normal VARIABLE N C

  1. #1
    Registered User
    Join Date
    Feb 2013
    Posts
    1

    VOLATILE vs Normal VARIABLE N C

    Friends,
    What is the difference between volatile variable and normal variable?

    I know the basic answer that the volatile var will get modified during execution time due to external conditions and it will avoid optimization.

    I went to many interviews and I am observing the same question where ever I go.But the interviewer is not satisfied with my ans.

    PLZ Post me something new Answers for volatile variable .

    Regards,
    Rajesh

  2. #2
    Algorithm Dissector iMalc's Avatar
    Join Date
    Dec 2005
    Location
    New Zealand
    Posts
    6,318
    "will get modified" is a bit strong.
    I think you perhaps get the idea but you just need to work on your explanation.
    Try posting the best description word-for-word that you can, in your own words.
    My homepage
    Advice: Take only as directed - If symptoms persist, please see your debugger

    Linus Torvalds: "But it clearly is the only right way. The fact that everybody else does it some other way only means that they are wrong"

  3. #3
    Registered User
    Join Date
    Nov 2011
    Location
    Saratoga, California, USA
    Posts
    334
    Perhaps some these will give you a bit more depth to your answer:

    Quote Originally Posted by MSDN
    The compiler assumes that, at any point in the program, a volatile variable can be accessed by an unknown process that uses or modifies its value. Therefore, regardless of the optimizations specified on the command line, the code for each assignment to or reference of a volatile variable must be generated even if it appears to have no effect.
    Quote Originally Posted by IBM
    The volatile qualifier maintains consistency of memory access to data objects. Volatile objects are read from memory each time their value is needed, and written back to memory each time they are changed. The volatile qualifier declares a data object that can have its value changed in ways outside the control or detection of the compiler (such as a variable updated by the system clock). The compiler is thereby notified not to apply certain optimizations to code referring to the object.


  4. #4
    Registered User
    Join Date
    Nov 2012
    Posts
    1,393
    Maybe it is best to consider a small example:

    Code:
    int main(void)
    {
        volatile int x;
        x = 3;
        x += 4;
        printf("The answer is %d\n", x);
        return EXIT_SUCCESS;
    }
    Try to compile this program (with optimizations turned on) and then look at disassembly output. For gcc you can do this with `objdump -D' on the executable produced.

    Code:
    406a2c:       55                      push   %ebp
      406a2d:       89 e5                   mov    %esp,%ebp
      406a2f:       83 e4 f0                and    $0xfffffff0,%esp
      406a32:       83 ec 20                sub    $0x20,%esp
      406a35:       e8 46 af ff ff          call   401980 <___main>
      406a3a:       c7 44 24 1c 03 00 00    movl   $0x3,0x1c(%esp)
      406a41:       00
      406a42:       8b 44 24 1c             mov    0x1c(%esp),%eax
      406a46:       83 c0 04                add    $0x4,%eax
      406a49:       89 44 24 1c             mov    %eax,0x1c(%esp)
      406a4d:       8b 44 24 1c             mov    0x1c(%esp),%eax
      406a51:       89 44 24 04             mov    %eax,0x4(%esp)
      406a55:       c7 04 24 64 80 40 00    movl   $0x408064,(%esp)
      406a5c:       e8 4f a9 ff ff          call   4013b0 <_printf.constprop.0>
    My assembler is a bit rusty, but it should be clear that distinct operations are being performed on each of the operands 4 and 3, and an `add' operation is being executed in the CPU.

    Now if you take out volatile and recompile, you get the following simplified output
    Code:
    406a35:       e8 46 af ff ff          call   401980 <___main>
      406a3a:       c7 44 24 04 07 00 00    movl   $0x7,0x4(%esp)
      406a41:       00
      406a42:       c7 04 24 64 80 40 00    movl   $0x408064,(%esp)
      406a49:       e8 62 a9 ff ff          call   4013b0 <_printf.constprop.0>
    Now, the compiler can make the trivial optimization and simply load the final result into a register. No mathematical operation is needed.

    In reality you wouldn't use volatile in this way, but it is just to demonstrate.

  5. #5
    Registered User
    Join Date
    Nov 2012
    Posts
    54
    how to turn on optimizations in turbo c 3.0?

  6. #6
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,659
    The best optimisation for TurboC is to find the top-level directory of where you installed it, then delete it to improve the amount of disk space you have available.

    Then choose one (or more) of the following, and start programming in the modern world.
    Visual Studio Express 2012 Products | Microsoft Visual Studio
    smorgasbordet - Pelles C
    Code::Blocks
    Orwell Dev-C++ | Free Development software downloads at SourceForge.net

    On the subject of explaining things, can you explain this?
    extern const volatile int clock;
    If you can, then you probably understand what is going on.

    Oh wait, you're not the OP, you're just an interloper.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  7. #7
    Registered User
    Join Date
    Mar 2011
    Posts
    546
    here's the best explanation i could google up in 5 seconds. if you can spit all this out on an interview, they will be impressed.
    Combining C’s volatile and const Keywords « Barr Code

  8. #8
    Registered User Codeplug's Avatar
    Join Date
    Mar 2003
    Posts
    4,981
    My 2¢...
    "volatile can be used in signal handlers to modify globals of type volatile sig_atomic_t"
    "volatile is mostly used for memory mapped I/O to hardware (registers, buses, etc..)"
    "the compiler must obey program order when issuing reads and writes to volatile variables"
    "volatile has nothing to do with multi-threading or synchronization"

    gg

  9. #9
    Registered User Codeplug's Avatar
    Join Date
    Mar 2003
    Posts
    4,981
    >> Combining C’s volatile and const Keywords « Barr Code
    There are a couple of content issues on that page:

    It is important to use volatile to declare all variables that are shared by asynchronous software entities, which is important in any kind of multithreaded programming. (Remember, though, that access to global variables shared by tasks or with an ISR must always also be controlled via a mutex or interrupt disable, respectively.)
    Mentioning multi-threading and mutex's in this context is erroneous. If proper synchronization is protecting a variable, then volatile is not needed - it just inhibits the optimizer.

    (#2) Read-Only Shared-Memory Buffer
    Another use for a combination of const and volatile is ...
    That whole section is ridiculous and false. If multiple threads access read-only memory locations, then no synchronization is needed - and adding volatile does nothing but inhibit the optimizer for no reason. If multiple threads access read-write memory locations, then only proper synchronization can insure determinism and consistency.

    >> "volatile has nothing to do with multi-threading or synchronization"

    gg

  10. #10
    Registered User
    Join Date
    Mar 2011
    Posts
    546
    Quote Originally Posted by Codeplug View Post
    >> "volatile has nothing to do with multi-threading or synchronization" gg
    correct. i didn't notice that. good catch

  11. #11
    Registered User
    Join Date
    Apr 2006
    Posts
    2,149
    Quote Originally Posted by Codeplug View Post
    That whole section is ridiculous and false. If multiple threads access read-only memory locations, then no synchronization is needed - and adding volatile does nothing but inhibit the optimizer for no reason. If multiple threads access read-write memory locations, then only proper synchronization can insure determinism and consistency.

    >> "volatile has nothing to do with multi-threading or synchronization"

    gg
    That's not quite right. You do need synchronization. You need to establish an ordering between the writer and the reader. Without that, there is no rule preventing the memory in question to go original->changed->original when accessed multiple times. Or alternatively, never seeing the change at all.

    For the multitheaded way of doing this in C11 you need an atomic memory read with memory_order_relaxed or stronger semantics. Atomic ensures that C sequencing rules are applicable to the atomic. In hardware, this makes access to the variable a memory load, just like volitile does. It may do more, as C11 does not specify how to implement atomics and memory consistency, but I know that some compilers do implement an atomic read on memory_order_relaxed as a normal memory load. So volitile does incidentally achieve the right result here.

    <EDIT>
    Alternatively, instead of making the whole block atomic, you could use another atomic variable to ensure ordering, and do a read on it with memory_order_acquire before reading from the shared memory. For a large block of memory, this is preferred.
    </EDIT>

    It's basically relying on guarantees of cache coherency provided by modern CPUs, but that isn't required by C. But then C doesn't have a lot to say about interprocess synchronization, so even using C11. There is no standard compliant way of achieving it. Using volitile here will do the right thing on (some) modern CPUs. An alternative would be to write in-line assembly to do the memory load and return the result by value.
    Last edited by King Mir; 02-08-2013 at 02:41 PM.
    It is too clear and so it is hard to see.
    A dunce once searched for fire with a lighted lantern.
    Had he known what fire was,
    He could have cooked his rice much sooner.

  12. #12
    Registered User Codeplug's Avatar
    Join Date
    Mar 2003
    Posts
    4,981
    >> That's not quite right. You do need synchronization.
    I'll assume you're referring to "That whole section is ridiculous and false."
    That section is talking about normal memory, that is constant and unchanging - "read-only". No synchronization and no volatile needed (according to Posix and C++11).

    >> You need to establish an ordering between the writer and the reader.
    Right, and that would imply the shared memory isn't read-only. So proper synchronization and no volatile will suffice.

    >> There is no standard compliant way of achieving it.
    I'm assuming that by "it" you mean "[achieving] synchronization via volatile". Since volatile has nothing to do with multi-threading in all standards that cover threads (Posix and C++11).

    >> Using volitile here will do the right thing on (some) modern CPUs.
    That's a stretch, by my definition of modern
    Memory ordering - Wikipedia, the free encyclopedia

    >> An alternative would be to write in-line assembly to ...
    ... "use the synchronization primitives provided by the CPU".
    Or use the synchronization primitives provided by your threading library.

    gg

  13. #13
    Registered User
    Join Date
    Apr 2006
    Posts
    2,149
    Quote Originally Posted by Codeplug View Post
    >> That's not quite right. You do need synchronization.
    I'll assume you're referring to "That whole section is ridiculous and false."
    That section is talking about normal memory, that is constant and unchanging - "read-only". No synchronization and no volatile needed (according to Posix and C++11).

    >> You need to establish an ordering between the writer and the reader.
    Right, and that would imply the shared memory isn't read-only. So proper synchronization and no volatile will suffice.
    The memory is read only to the reader process, but it has a writer process that updates it. That's why volitlile is used here. It's forcing memory read to actually read memory, instead of cacheing the value in a register, which increases the odds of seeing changes made by the other process.

    >> There is no standard compliant way of achieving it.
    I'm assuming that by "it" you mean "[achieving] synchronization via volatile". Since volatile has nothing to do with multi-threading in all standards that cover threads (Posix and C++11).
    No, I mean receiving updates to a buffer written by another process. C and C++ 11 do not cover interprocess synchronization. (This is the C forum, so C11 is the relevant standard)

    >> Using volitile here will do the right thing on (some) modern CPUs.
    That's a stretch, by my definition of modern
    Memory ordering - Wikipedia, the free encyclopedia
    But reads from the volitile variable are still ordered. I was assuming that was enough, but you're right to highlight that assumption.

    >> An alternative would be to write in-line assembly to ...
    ... "use the synchronization primitives provided by the CPU".
    Or use the synchronization primitives provided by your threading library.

    gg
    Technically it'd be "use the memory sharing primitives provided by your interprocess communication library. But fair point.
    It is too clear and so it is hard to see.
    A dunce once searched for fire with a lighted lantern.
    Had he known what fire was,
    He could have cooked his rice much sooner.

  14. #14
    Registered User Codeplug's Avatar
    Join Date
    Mar 2003
    Posts
    4,981
    >> The memory is read only to the reader process, but it has a writer process that updates it.
    I see...

    >>[/b]That's why volitlile is used here. It's forcing memory read to actually read memory, instead of cacheing the value in a register, which increases the odds of seeing changes made by the other process.[/b]
    The problem is that volatile does not affect memory visibility - and both standards define this usage as undefined.

    >> No, I mean receiving updates to a buffer written by another process. C and C++ 11 do not cover interprocess synchronization.
    Sure it does (in my mind). The C++ standard has a defined memory model which defines what a "memory location" is. Doesn't matter if that memory location is accessed by threads of the same process, or threads from multiple processes (by my reckoning).

    >> But reads from the volitile variable are still ordered.
    Volatile only affects compiler ordering, or the ordering of the emitted instructions. It doesn't affect visibility or re-ordering that can occur at the hardware level.

    >> Technically it'd be "use the memory sharing primitives provided by your interprocess communication library.
    If two threads are accessing the same memory location, it doesn't matter if they are in the same or different processes. You can use the same synchronizing CPU instructions in either case - the CPU doesn't care. However, if you were using synchronization primitives from your OS or threading library, then inter/intra process may make a difference in the primitives you use (eg. CRITICAL_SECTION vs CreateMutex() in Win32).

    gg

  15. #15
    Registered User
    Join Date
    Apr 2006
    Posts
    2,149
    Quote Originally Posted by Codeplug View Post
    >> The memory is read only to the reader process, but it has a writer process that updates it.
    I see...

    >>[/b]That's why volitlile is used here. It's forcing memory read to actually read memory, instead of cacheing the value in a register, which increases the odds of seeing changes made by the other process.[/b]
    The problem is that volatile does not affect memory visibility - and both standards define this usage as undefined.
    Yes it does. That's the whole point. If memory changes due to a device, volatile is what ensures that change is seen.

    >> No, I mean receiving updates to a buffer written by another process. C and C++ 11 do not cover interprocess synchronization.
    Sure it does (in my mind). The C++ standard has a defined memory model which defines what a "memory location" is. Doesn't matter if that memory location is accessed by threads of the same process, or threads from multiple processes (by my reckoning).
    I concede, the principles apply. It's not strictly defined what it means to be sequenced relative to another thread in another process, but you can extrapolate. So that means you could share atomic primitives instead of using volatile.

    >> But reads from the volitile variable are still ordered.
    Volatile only affects compiler ordering, or the ordering of the emitted instructions. It doesn't affect visibility or re-ordering that can occur at the hardware level.
    Right, volitle has no effect on ordering, but the behavior of a relaxed ordering atomic read doesn't either. So the two have the same behavior, which is a memory load and nothing else. But what I said is true, reads from the variable are still ordered. This is not special to volitile, it's a a matter of data dependency and sequencing.

    >> Technically it'd be "use the memory sharing primitives provided by your interprocess communication library.
    If two threads are accessing the same memory location, it doesn't matter if they are in the same or different processes. You can use the same synchronizing CPU instructions in either case - the CPU doesn't care. However, if you were using synchronization primitives from your OS or threading library, then inter/intra process may make a difference in the primitives you use (eg. CRITICAL_SECTION vs CreateMutex() in Win32).

    gg
    Fair point.
    It is too clear and so it is hard to see.
    A dunce once searched for fire with a lighted lantern.
    Had he known what fire was,
    He could have cooked his rice much sooner.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Doubt regarding structure padding and normal variable
    By karthik537 in forum C Programming
    Replies: 6
    Last Post: 10-03-2012, 08:26 AM
  2. Volatile Variable.
    By nagavardna in forum C Programming
    Replies: 2
    Last Post: 04-19-2012, 03:34 AM
  3. Difference between global variable and volatile
    By karthik537 in forum C Programming
    Replies: 4
    Last Post: 02-29-2012, 11:28 AM
  4. Guaranteed read from volatile variable
    By cyberfish in forum C++ Programming
    Replies: 17
    Last Post: 08-15-2011, 09:00 AM
  5. Normal maps: Get normal x/y/z from color
    By Devils Child in forum Game Programming
    Replies: 2
    Last Post: 08-09-2009, 12:01 PM