As if rule
The “as-if” rule allows flexibility in C++ implementations. The “as-if” rule is: “Implementations are free to reorder or even rewrite a program’s instructions, so long as the resulting program still behaves as if it were exactly as written.”
For example, consider the following program:
a = 10 b = 20
The “as-if” rule means that the lines setting
20 don’t necessarily need to be run in that order.
b may be set first, then
b may not be set until after the line that prints the value of
All that has to happen is that
a must be set to
10 before the line that prints the value of
b must be set to
20 before its value is printed (because in both cases, the value cannot be printed before it is set), and the two print statements cannot be swapped (otherwise the program’s output would be different).
Beyond those restrictions, it doesn’t matter in what order things happen.
You can shuffle the instructions around, and the program’s output will still be the same.
This is a very important factor in C++’s efficiency. Take another look at the example above. If you think about it, it’s even possible to completely eliminate both variables – they never change, after all, and the values are used just a few lines later. The code could be:
a = 10 b = 20
and it would produce exactly the same observable output, while saving the memory and extra instructions associated with the two variables.
The “as-if” rule allows you to write what you mean in the clearest, most logical way, while giving the compiler the freedom to rearrange things, or even eliminate things, to produce the most efficient program.