I was looking up the keyword volatile
and what it\'s for, and the answer I got was pretty much:
It\'s used to prevent the compiler from o
The observable behavior of a C++ program is determined by read and writes to volatile variables, and any calls to input/output functions.
What this entails is that all reads and writes to volatile variables must happen in the order they appear in code, and they must happen. (If a compiler broke one of those rules, it would be breaking the as-if rule.)
That's all. It's used when you need to indicate that reading or writing a variable is to be seen as an observable effect. (Note, the "C++ and the Perils of Double-Checked Locking" article touches on this quite a bit.)
So to answer the title question, it prevents any optimization that might re-order the evaluation of volatile variables relative to other volatile variables.
That means a compiler that changes:
int x = 2;
volatile int y = 5;
x = 5;
y = 7;
To
int x = 5;
volatile int y = 5;
y = 7;
Is fine, since the value of x
is not part of the observable behavior (it's not volatile). What wouldn't be fine is changing the assignment from 5 to an assignment to 7, because that write of 5 is an observable effect.