What is volatile?

A detailed description please?
volatile is used to signify to the compiler not to optimize use of the variable that is declared volatile. For example, given the code:

1
2
3
4
5
6
7
8
int a;
int b;

{
a = 5;
b = 6;
// other code
}


The order in which the memory locations referenced by a and b are written with the values 5 and 6 respectively is undefined; moreover, the values 5 and 6 might not be written back to memory until after "other code" executes. The compiler is free to optimize things.

Another example (stupid example, but demonstrates the point):

1
2
3
4
bool doneYet = false;
while( !doneYet ) {
   // twiddle thumbs (but do not touch doneYet)
}


The compiler could read the memory location referenced by doneYet into a register once, then never read it again. The reason is because an optimizing compiler could see that the body of the loop cannot affect doneYet, thus the compiler could suppress reloading doneYet into a register every time through the loop.

By declaring a and b as volatile int and doneYet as volatile bool, the compiler is guaranteed to write 5 to a's memory location immediately, 6 to b's memory location immediately, and actually read the memory location referenced by doneYet every time.



How could someone benefit from that??
Sometimes, it's necessary to guarantee that a variable is up to date. For example, when a different thread requires that it has a certain value.
Topic archived. No new replies allowed.