confusion about volatile

Thread Starter

crazyengineer

Joined Dec 29, 2010
156
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?
 

AlexR

Joined Jan 16, 2008
732
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.
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.
Otherwise I don't understand why you use it. Can anyone give a more in depth explanation?
I suggest you take a look at this link for a brief but clear explanation of the volatile keyword. http://www.eetimes.com/discussion/beginner-s-corner/4023801/Introduction-to-the-Volatile-Keyword
 

nsaspook

Joined Aug 27, 2009
16,473
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?
Simple example. Look at the disassembly listing window for the effect of volatile on the code.

http://www.flickr.com//photos/nsaspook/sets/72157627096455182/show/

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.
 

ErnieM

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

Rich (BB code):
    { 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:

Rich (BB code):
    { for(volatile int i=0;i<255;i++); }
And for PIC compiler peoples:

Rich (BB code):
    { volatile int i; for(i=0;i<255;i++); }
 
Top