When the same piece of code is compiled with optimizations fully disabled (g++ -O0) and then again with the optimizations fully enabled (g++ -O3), how can the logic of the source code itself be changed?
For example, compilers can
- unwind loops and
- do constant folding.
These two optimizations make the code perform faster without affecting the integrity of the original source code. Any code that runs without these optimizations will run with them enabled.
But, compiler optimizations can also affect code logic. Here are two examples that I know of:
- Removing copy constructors and assignment operators from temporaries may remove possible side-effects.
- Rearranging arithmetic containing floating point values may affect floating point error (hopefully requires
-ffast-mathargument).
I was very surprised, and lucky, to learn about these because they could become huge potential gotchas in the wrong situation.
So I want to know, are there any other cases where c++ compiler optimizations will affect code logic? I’m specifically looking for information about c++11 (without any undefined behaviour) under the g++ compiler, but tips for other compilers are welcome.
The "as-if" Rule:
However, the standard mentions one optimization which is allowed, and which breaks the "as-if" rule: