Namespaces
Variants
Actions

As if rule

From cppreference.com


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:

#include <iostream>
 
int main()
{
    int a = 10;
    int b = 20;
 
    std::cout << "a = " << a << '\n';
    std::cout << "b = " << b << '\n';
 
    return 0;
}

Output:

a = 10
b = 20

The “as-if” rule means that the lines setting a to 10 and b to 20 don’t necessarily need to be run in that order. b may be set first, then a. In fact, b may not be set until after the line that prints the value of a! All that has to happen is that a must be set to 10 before the line that prints the value of a, 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:

#include <iostream>
 
int main()
{
    std::cout << "a = " << 10 << '\n';
    std::cout << "b = " << 20 << '\n';
 
    return 0;
}

Output:

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.