IT lexicon › Programming › As-if rule

As-if rule

Programming På svenska → Updated: 2026-11-06

The principle in the C and C++ standards that lets the compiler rewrite a program any way it likes, provided the observable behavior stays the same.

The standard describes an abstract machine that executes the code line by line. The real program only has to behave as if it did. What counts as observable is narrow: accesses to volatile objects, data written to files, and interaction with the terminal. Everything else — intermediate values, the order of computations, whether a loop survives — is the compiler's business. It is the legal basis for nearly every optimization, from constant folding to turning a loop that sums 1 to n into a closed-form formula.

The rule also explains why undefined behavior is so dangerous: a program that has it has no behavior left to preserve. The best-known exception in the other direction is copy elision, which may remove a copy constructor even when that constructor has side effects.

← Back to the lexicon