Thursday, September 25, 2008

Volatile variable

It may be modified externally from the declaring variable (object). It tells the compiler not to cache this variable in a register but instead to read the value of the variable from memory each and every time the variable is used.
Variables declared to be volatile will not be optimized by the compiler because the compiler must assume that their values can change at any time.
volatile int a = 0;
while (!a)

The value 'int a' is read from memory for each loop iteration. If volatile was not specified then it is likely that the compiler would generate optimized code which would read the value of the 'int a' once, temporarily store this in a register and then use the register copy during each iteration. With 'volatile', 'a' could be changed in another thread.
Examples of where volatile is often used:
compiler will not optimized 'int a'. If compile does optimization, it finds (a!=0) is always TRUE. The compile may totally remove this line. Each time the value is to be read, the value should be read directly from memory/register.
some above contents are from following link, also check wiki example
The above code (main thread with volatile, and another thread to change it). It works in debug mode, but 'a' always equals to 0 in release mode? ( i didn't get it)

[updated on Nov. 30, 09, from]
1. can a parameter be both volatile and constant?
Yes, a read-only status register, it changes unexpectedly and you should not attempt to modify it

2. can a pointer be volatile?
yes, example: an interruption service routine modifies the pointer to a buffer.

Examples of volatile variables are:
  • Hardware registers in peripherals (for example, status registers)
  • Non-automatic variables referenced within an interrupt service routine
  • Variables shared by multiple tasks in a multi-threaded application
A good article is here

Note: the individual fields of a struct, as well as the entire struct can be declared volatile.
[update: 2/28/2013]
It tells the compiler, don't optimize this part.

No comments:

Post a Comment