NPS
NPS

Reputation: 6355

Does "volatile" only prevent from compiler optimisation?

I know there are meny questions about volatile but I think I ask a different one. I don't ask what it does (in general), my question is: does the volatile keyword ONLY prevent compiler from optimising code which uses a volatile variable or is there ANYTHING else that this keyword does?

Upvotes: 0

Views: 342

Answers (2)

Kerrek SB
Kerrek SB

Reputation: 477512

Leave the compiler out. The compiler is the least interesting aspect of C++ and doesn't usually play a role in how you think about the language.

The language has this to say about volatile:

1.9, 1 paraphrased:

Access to volatile objects are evaluated strictly according to the rules of the abstract machine.

...

Accessing an object designated by a volatile glvalue is side effect, which is a changes in the state of the execution environment.

...

The implementation may assume that any thread will eventually do one of the following:

  • ...
  • access or modify a volatile object
  • ...

So, as you can see, volatile objects are in some sense part of the interface of your program with the outside world. One of the consequences is that volatile access is given certain ordering guarantees, but that's just a detail. The bigger picture is that volatile means "may interact with the environment".

Upvotes: 4

Stack Overflow is garbage
Stack Overflow is garbage

Reputation: 248219

Memory accesses (reads and writes) against volatile variables are guaranteed to occur in the order specified in the program. That's all, really. This means that the compiler is not allowed to reorder them (disabling certain compiler optimizations), but also that additional instructions must be emitted to prevent the CPU from reordering them.

Note that this doesn't prevent all the non-volatile memory accesses from being reordered around the volatile ones. It only ensures that volatile memory accesses will not be reordered with respect to each others (and that they won't be optimized away entirely)

Upvotes: 2

Related Questions