What does type qualifier volatile indicate to the compiler?

Showing Answers 1 - 9 of 9 Answers

vchiranjeevireddy

  • Sep 25th, 2007
 

It is a way of instructing the compiler not optmize this varaiable.

The compiler doesn't touch variables if they don't change oftenly in loops as part of it's optimization technique.

With this voltaile qualifier,we recommend the compiler touch this variable in all it's iteration.

  Was this answer useful?  Yes

hemanth

  • Sep 25th, 2007
 

Indicate that a variable can be changed by a background routine.

  Was this answer useful?  Yes

kbjarnason

  • Jul 1st, 2010
 

An optimizing compiler can examine the flow of code and (in many cases) determine whether a variable is actually modified or not; if not, then there's no reason to read the value from memory more than once.  Since reading from memory is typically slower than reading from a register, redundant memory accesses tend to be avoided wherever possible.

What happens, however, if the variable's value _is_ changed? 

One (highly system specific) example would be creating a pointer which points to a status register, a real-time clock or some other system data which changes regularly, outside the program's control.

In such a case, the program's _code_ gives no indication that the variable's value will ever change, so the optimizing compiler will happily optimize it that way - read it once, store it in a register, never read it again.  Oops.

char *ptr = someaddress;

while ( *ptr != 'f' )
   ;

This is either a no-op or an infinite loop; if *ptr is 'f' initially, the code falls through; if it's not 'f' initially, the code loops forever.


By declaring the variable volatile, however, you tell the complier that the value of the variable _can_ change in some manner not obvious from the source code, so when it tries to do its magic, it knows it cannot simply "read and record" the value - it has to re-read the vaule every time the variable is used.

volatile char *ptr = someaddress;

while ( *ptr != 'f' )
    ;

Now the code will actually re-read the memory pointed to by ptr, and if it ever changes to an 'f', the loop will actually end - but we had to force the compiler to actually re-read the memory address by telling the compiler the value there is volatile.

  Was this answer useful?  Yes

Give your answer:

If you think the above answer is not correct, Please select a reason and add your answer below.

 

Related Answered Questions

 

Related Open Questions