Is the compiler allowed to optimize this (according to the C++17 standard):
int fn() {
volatile int x = 0;
return x;
}
to this?
This loop can be optimised away by the as-if rule because it has no observable behaviour:
for (unsigned i = 0; i < n; ++i) { bool looped = true; }
This one cannot:
for (unsigned i = 0; i < n; ++i) { volatile bool looped = true; }
The second loop does something on every iteration, which means the loop takes O(n) time. I have no idea what the constant is, but I can measure it and then I have a way of busy looping for a (more or less) known amount of time.
I can do that because the standard says that access to volatiles must happen, in order. If a compiler were to decide that in this case the standard didn't apply, I think I would have the right to file a bug report.
If the compiler chooses to put looped into a register, I suppose I have no good argument against that. But it still must set the value of that register to 1 for every loop iteration.