confusion about volatile

Discussion in 'Programmer's Corner' started by crazyengineer, Aug 15, 2011.

  1. crazyengineer

    Thread Starter Member

    Dec 29, 2010
    I'm very confuse about volatile type variables. I understand you use it a lot when working with variables that changes alot and in embedded systems. Otherwise I don't understand why you use it. Can anyone give a more in depth explanation?
  2. AlexR

    Well-Known Member

    Jan 16, 2008
    This is not strictly true, the volatile tag should be used when variables can change outside of direct program control irrespective of how often they change because any half decent compiler keeps track of the variables and optimises out or caches any variable that to its knowledge does not change. In embedded systems I/O ports and peripheral registers must be marked volatile as should global variables that are used by interrupt routines.
    I suggest you take a look at this link for a brief but clear explanation of the volatile keyword.
  3. nsaspook

    AAC Fanatic!

    Aug 27, 2009
    Simple example. Look at the disassembly listing window for the effect of volatile on the code.

    With no 'volatile' it optimizes out the second x=y.
    With 'volatile' it leaves in the second x=y even if it might be redundant.

    So volatile in most embedded (8-16 bit) targeted compilers tells the optimizer to not change the (unknown to the compiler) intent of the code writer and to leave the code flow as written.
  4. ErnieM

    AAC Fanatic!

    Apr 24, 2011
    nsaspook has a very good point there. Consider the following fragment to introduce some delay:

    Code ( (Unknown Language)):
    1.     { for(int i=0;i<255;i++); }
    Putting the loop in {brackets} creates and frees the i variable inline (PIC compiler users need two statements for this). A good optimizing compiler will translate to NO CODE, optimize away your whole delay as i never gets used anywhere.

    Thus proper usage would be:

    Code ( (Unknown Language)):
    1.     { for(volatile int i=0;i<255;i++); }
    And for PIC compiler peoples:

    Code ( (Unknown Language)):
    1.     { volatile int i; for(i=0;i<255;i++); }