So according to the C++ standard, can compiler eliminates the volatile int c?
No. volatile
-qualified objects are used for reading from or writing to the hardware, and the side-effects of assigning a volatile
object are observable.
Therefore, in compliance with the constraints on optimizations placed by the so-called "as-if" rule, conforming implementations are not allowed to optimize away c
. The "as-if" rule is formally introduced in Paragraph 1.9/1 of the C++11 Standard:
The semantic descriptions in this International Standard define a parameterized nondeterministic abstract
machine. This International Standard places no requirement on the structure of conforming implementations.
In particular, they need not copy or emulate the structure of the abstract machine. Rather, conforming
implementations are required to emulate (only) the observable behavior of the abstract machine as explained
below
And the concept of "observable behavior" is defined in paragraph 1.9/8:
The least requirements on a conforming implementation are:
— Access to volatile objects are evaluated strictly according to the rules of the abstract machine.
— At program termination, all data written into files shall be identical to one of the possible results that
execution of the program according to the abstract semantics would have produced.
— The input and output dynamics of interactive devices shall take place in such a fashion that prompting
output is actually delivered before a program waits for input. What constitutes an interactive device
is implementation-defined.
These collectively are referred to as the observable behavior of the program. [...]
Since access to volatile
objects must be evaluated strictly according to the rules of the abstract machine, compilers are not allowed to optimize away c
and the corresponding assignment operation.