Lesson 200 +10 XP

Constant Expressions and the As-If Rule

Constant Expressions and the As-If Rule

A compiler may rewrite your program nearly any way it wants, as long as the behavior you observe stays the same. That freedom is the as-if rule.

The as-if rule

The standard says an implementation may do whatever it wants to your code as if the rules were followed exactly, provided observable behavior is unchanged. This one sentence licenses every optimization: inlining, reordering, constant folding.

Constant expressions

A constant expression is a value known entirely at compile time:

constexpr int square(int n) {
    return n * n;
}

constexpr int answer = square(5);   // computed at compile time

constexpr lets the compiler evaluate the function early, turning square(5) into the literal 25.

Why constexpr matters

constexpr auto limit = 10;
int table[limit];        // size must be known at compile time

Because limit is a constant expression, it can size an array.

As-if in action

int x = 5;
int y = x + 1;   // the compiler may simply store 6

Even though the source says x + 1, the as-if rule lets the optimizer keep y = 6 while the observable result is identical.

TL;DR

  • The as-if rule lets the compiler optimize so long as observable behavior is identical.
  • A constant expression is a value known at compile time.
  • constexpr functions may be evaluated by the compiler.
  • Constant expressions can size arrays and cut runtime costs.
  • Write clear code; let the optimizer make it fast.