Is the compiler allowed to optimize this (according to the C++17 standard):
int fn() {
volatile int x = 0;
return x;
}
to this?
I beg to dissent with the majority opinion, despite the full understanding that volatile means observable I/O.
If you have this code:
{
volatile int x;
x = 0;
}
I believe the compiler can optimize it away under the as-if rule, assuming that:
The volatile variable is not otherwise made visible externally via e.g. pointers (which is obviously not a problem here since there is no such thing in the given scope)
The compiler does not provide you with a mechanism for externally accessing that volatile
The rationale is simply that you couldn't observe the difference anyway, due to criterion #2.
However, in your compiler, criterion #2 may not be satisfied! The compiler may try to provide you with extra guarantees about observing volatile variables from the "outside", such as by analyzing the stack. In such situations, the behavior really is observable, so it cannot be optimized away.
Now the question is, is the following code any different than the above?
{
volatile int x = 0;
}
I believe I've observed different behavior for this in Visual C++ with respect to optimization, but I'm not entirely sure on what grounds. It may be that initialization does not count as "access"? I'm not sure. This may be worth a separate question if you're interested, but otherwise I believe the answer is as I explained above.