# Evaluation Order, Sequencing & Undefined Side Effects

> Separate operator precedence from evaluation order, read C++17's tightened sequencing guarantees, and avoid unsequenced undefined behavior.

- **Source:** C++ Atlas (https://cppatlas.com/topics/evaluation-order)
- **Track:** Expressions and functions
- **Estimated reading time:** 7 minutes
- **ISO C++ clauses:** [intro.execution] (https://eel.is/c++draft/intro.execution), [expr.call] (https://eel.is/c++draft/expr.call), [expr.ass] (https://eel.is/c++draft/expr.ass), [expr.log.and] (https://eel.is/c++draft/expr.log.and), [expr.cond] (https://eel.is/c++draft/expr.cond), [expr.comma] (https://eel.is/c++draft/expr.comma)
- **cppreference links:** [Order of evaluation](https://en.cppreference.com/w/cpp/language/eval_order), [Operator Precedence](https://en.cppreference.com/w/cpp/language/operator_precedence), [Increment/decrement operators](https://en.cppreference.com/w/cpp/language/operator_incdec), [Logical operators](https://en.cppreference.com/w/cpp/language/operator_logical)
- **Prerequisites:** value-categories

Many C++ bugs start with a simple confusion: reading an expression's operator precedence as if it were a runtime schedule. When you write `f() + g() * h()`, operator precedence forces `*` to bind tighter than `+`, grouping the expression as `f() + (g() * h())`. Precedence builds the syntax tree, not the execution timeline. The compiler is completely free to evaluate `f()` before `g()`, after `h()`, or between them, because `+` and `*` impose no ordering constraint between their subexpressions.

> **Mental model.** Precedence and associativity decide *which operands belong to which operator*; sequencing decides *when side effects and value computations happen in time*. Two expressions can share the exact same parse tree on every compiler while running their leaf calls in opposite orders under different optimization flags.

## Sequenced-before, unsequenced, and indeterminately sequenced

To talk precisely about time inside a single thread, the C++ standard defines every evaluation as two steps: **value computation** (producing the result) and **initiation of side effects** (modifying an object, reading a `volatile` glvalue, or invoking I/O). Between any two evaluations `A` and `B`, `[intro.execution]` defines exactly three possible ordering relationships:

1. **Sequenced before.** Both the value computation and every side effect of `A` finish completely before `B` begins. Semicolons (`;`), full-expression boundaries, and specific operators establish this strict edge.
2. **Indeterminately sequenced.** Either `A` is sequenced before `B`, or `B` is sequenced before `A`, and the compiler does not have to tell you which—even across different call sites in the same binary. Crucially, `A` and `B` **cannot overlap** or interleave instructions.
3. **Unsequenced.** `A` and `B` may execute in any order and may interleave step-by-step on the abstract machine.

That third category is where undefined behavior lives. Under `[intro.execution]/10`, if a side effect on a scalar object is **unsequenced** relative to either a different side effect on the same scalar object or a value computation using the value of that same scalar object, the behavior is **undefined**—not unspecified, not implementation-defined, completely undefined.

> **Standardese.** "If a side effect on a memory location is unsequenced relative to either another side effect on the same memory location or a value computation using the value of any object in the same memory location, and they are not potentially concurrent, the behavior is undefined." — `[intro.execution]`

```cpp
int f();
int g();
int h();

void demo(int i) {
    // Parse tree is f() + (g() * h()), yet f(), g(), and h()
    // are indeterminately sequenced relative to one another.
    int total = f() + g() * h();

    // Undefined behavior: two unsequenced mutations/reads of scalar 'i'.
    // int bad = i++ + ++i;
    // int also_bad = i + i++;
    (void)total;
    (void)i;
}
```

## What C++17 guaranteed—and what it did not

Before C++17, idioms as ordinary as `std::cout << a() << b()` or `map[key] = build()` carried subtle traps because almost every binary operator left its operands unsequenced. C++17 (via P0145R3) tightened the abstract machine so postfix chains, shifts, and assignments have predictable order, while intentionally leaving arithmetic and comparison operators unsequenced so optimizers can keep scheduling registers freely.

| Expression form | Sequencing rule since C++17 | Notes |
| --- | --- | --- |
| `a.b`, `a->b`, `a->*b`, `a.*b` | `a` before `b` | Member access proceeds left-to-right |
| `a[b]` | `a` before `b` | Applies to built-in and overloaded `operator[]` |
| `a << b`, `a >> b` | `a` before `b` | Stream chaining `cout << f() << g()` calls `f()` first |
| `a = b`, `a @= b` | `b` before `a` | Right operand completes before left operand |
| `a(b1, b2, ...)` | `a` before all `bi`; `bi` indeterminately sequenced | Arguments cannot interleave each other |
| `{e1, e2, ...}` | `e1` before `e2` before `...` | Braced-init-lists evaluate strictly left-to-right |
| `a + b`, `a * b`, `a < b` | Unsequenced (function calls indeterminately sequenced) | Never mutate and read the same scalar across sides |

Look closely at the assignment row in that summary. Both built-in assignments and operator-syntax assignments (`a = b`, `a += b`) evaluate their **right-hand operand completely before their left-hand operand** (`[expr.ass]/1` combined with `[over.match.oper]/2`). Even in `v[i] = i++;`, C++17 sequences `i++` (computing `0` and incrementing `i` to `1`) before evaluating `v[i]`, storing `0` into `v[1]`. That was undefined behavior in C++14; it is well-defined in C++17 and later, though still hostile to human readers and worth splitting into two clear statements.

```cpp
#include <iostream>

struct Sink {
    Sink& operator=(const Sink&) { return *this; }
};

Sink& pick_target(Sink& s) {
    std::cout << "lhs ";
    return s;
}

Sink build_value() {
    std::cout << "rhs ";
    return Sink{};
}

int step(const char* tag, int value) {
    std::cout << tag << ' ';
    return value;
}

void sequencing_demo() {
    Sink target;
    pick_target(target) = build_value(); // Prints: rhs lhs

    std::cout << step("first", 1) << step("second", 2) << '\n'; // Prints: first 1second 2

    int ordered[] = { step("one", 1), step("two", 2), step("three", 3) };
    (void)ordered;
}
```

## Function arguments and the smart-pointer classic

Function-call syntax `f(a1, a2, ...)` obeys two distinct rules. First, the postfix expression `f` itself—which might compute a function pointer or callable object—is sequenced before every argument expression and before every default argument (`[expr.call]/7`). Second, the argument expressions `a1`, `a2`, and so on are **indeterminately sequenced** relative to one another, rather than unsequenced.

That distinction solved a notorious pre-C++17 memory leak:

```cpp
#include <memory>

struct Widget { explicit Widget(int) {} };
int compute_or_throw();
void consume(std::shared_ptr<Widget>, int);

void call_site() {
    // Pre-C++17: compiler could run (1) new Widget{1}, (2) compute_or_throw(),
    // and only then (3) shared_ptr ctor — leaking Widget if step 2 threw!
    // C++17+: argument 1 and argument 2 cannot interleave, closing the leak.
    consume(std::shared_ptr<Widget>(new Widget{1}), compute_or_throw());

    // Still cleaner and avoids a separate control-block allocation:
    consume(std::make_shared<Widget>(1), compute_or_throw());
}
```

Notice what C++17 did *not* change: `compute_or_throw()` is still allowed to run before `new Widget{1}`, or after `std::shared_ptr<Widget>(new Widget{1})` finishes constructing. Only interleaving the steps inside one argument with the steps of another argument was outlawed. Also remember that parameter initialization completes for every argument before the function body begins executing, and parameter destruction order at the end of the call is implementation-defined (though commonly right-to-left on the Itanium ABI and left-to-right on MSVC).

## Short-circuiting, commas, and overloaded operators

Four built-in operators enforce strict left-to-right control flow: logical AND (`a && b`), logical OR (`a || b`), the ternary conditional (`a ? b : c`), and the comma operator (`a, b`). For built-in `&&` and `||`, `a` is sequenced before `b`, and `b` is never evaluated at all if `a` settles the boolean outcome. Similarly, `a ? b : c` completes `a` and all of its side effects before starting whichever single branch (`b` or `c`) is selected. Built-in `a, b` evaluates `a`, discards its result, and sequences `a` before `b`.

> **Pitfall.** Overloading `operator&&`, `operator||`, or `operator,` breaks short-circuiting. While C++17 preserves left-before-right operand sequencing in `[over.match.oper]/2`, user-defined `operator&&` is still a function call whose parameters must both be initialized before entry—so the right-hand operand always evaluates, even when the left-hand operand is logically false.

Finally, keep the **comma operator** separate from **comma separators**. The commas inside `foo(a(), b())` separate function arguments and leave their order unspecified (indeterminately sequenced). The commas inside `{a(), b()}` separate braced-initializer clauses, which *are* guaranteed left-to-right (`[dcl.init.list]/4`). Only `(a(), b())`—wrapped in parentheses as a single expression—invokes the comma operator itself.

## What to remember

- **Precedence is syntax, sequencing is time.** Operators like `+` and `*` bind operands into a tree without ordering their subexpressions.
- **Unsequenced scalar conflicts are UB.** Never read or write a scalar object more than once across unsequenced subexpressions such as `i++ + ++i`.
- **C++17 fixed chains, shifts, and assignments.** Left-to-right holds for `.`, `->`, `[]`, `<<`, `>>`, and `{...}`, while `=` and `@=` evaluate right-before-left.
- **Function arguments still have no fixed order.** Arguments cannot interleave after C++17, yet any argument may still finish before its siblings start.
- **Never overload `&&`, `||`, or `,`.** Custom overloads evaluate both operands eagerly and defeat the short-circuit contract readers expect.

## Concept Map Outline

- **Evaluation Order:** C++ separates syntax grouping from runtime sequencing and defines strict rules for side-effect visibility.
  - **Precedence vs Ordering:** Syntax trees bind operands to operators without dictating which subexpression runs first.
    - **Precedence builds parse tree:** Higher-precedence operators claim neighboring operands before lower-precedence operators.
    - **Associativity groups ties:** Left or right associativity resolves equal-precedence chains such as a - b - c.
    - **Order picks runtime schedule:** The optimizer schedules subexpressions freely unless a sequencing edge constrains them.
  - **Sequencing Relations:** Every pair of single-thread evaluations is sequenced, indeterminately sequenced, or unsequenced.
    - **Sequenced before:** Value computation and all side effects of the first complete before the second starts.
    - **Indeterminately sequenced:** Either evaluation finishes before the other without interleaving instructions.
    - **Unsequenced conflicts:** Two unsequenced accesses to one scalar where at least one writes cause undefined behavior.
  - **C++17 Guarantees:** P0145R3 ordered postfix chains, shifts, assignments, and separated function arguments.
    - **Postfix and subscript left-first:** Member access and array indexing always finish evaluating the left object first.
    - **Shifts evaluate left-to-right:** Chained stream insertions and bit shifts sequence the left operand before the right.
    - **Assignment right-before-left:** Simple and compound assignments evaluate the right operand completely before the left.
    - **Arguments cannot interleave:** Each argument finishes without interleaving, preventing nested smart-pointer leaks.
  - **Short-Circuit & Lists:** Control-flow operators and braced initializers enforce deterministic left-to-right steps.
    - **Built-in logical operators:** Built-in && and || sequence left before right and skip the right when already decided.
    - **Ternary conditional:** The condition and its side effects complete before the single chosen branch evaluates.
    - **Braced initializer lists:** Clauses inside curly braces always evaluate strictly left-to-right.
  - **Overload Traps:** User-defined operators alter function-call timing and disable short-circuiting.
    - **Overloaded && evaluates eagerly:** Custom operator&& is a function call, so both operands evaluate even when the left is false.
    - **Overloaded ops keep order:** Operator syntax preserves the built-in operand order while function notation does not.

## Standardese Quiz Questions

### Question 1 [warmup] ([intro.execution], [expr.mul])

In `int x = a() + b() * c();` (C++23), what does operator precedence guarantee about runtime execution?

```cpp
int x = a() + b() * c();
```

A. `b()` and `c()` must both execute before `a()` executes.
B. `a()` must execute first because reading happens left-to-right.
C. The result of `b() * c()` is added to `a()`, while `a()`, `b()`, and `c()` may run in any order.
D. The expression is undefined behavior unless parentheses are added around `b() * c()`.

**Answer (C):** The result of `b() * c()` is added to `a()`, while `a()`, `b()`, and `c()` may run in any order.

**Why:** Operator precedence makes `*` bind tighter than `+`, building the syntax tree `a() + (b() * c())`. It does not schedule the three function calls: `a()`, `b()`, and `c()` are indeterminately sequenced and may run in any non-overlapping order.

### Question 2 [warmup] ([expr.shift], [over.match.oper])

Since C++17, what does `std::cout << first() << second() << '\n';` guarantee?

```cpp
int first();
int second();
std::cout << first() << second() << '\n';
```

A. `first()` is sequenced before `second()`, regardless of optimization level.
B. `first()` and `second()` are still indeterminately sequenced because `operator<<` is overloaded.
C. `second()` runs before `first()` because arguments bind right-to-left.
D. The behavior is unspecified unless `first()` and `second()` are `noexcept`.

**Answer (A):** `first()` is sequenced before `second()`, regardless of optimization level.

**Why:** C++17 made `E1 << E2` sequence `E1` before `E2`, and `[over.match.oper]/2` applies that built-in sequencing rule to overloaded operator syntax as well. Therefore `std::cout << first()` completes before `second()` starts.

### Question 3 [tricky] ([expr.log.and], [over.match.oper])

Consider a type `Flag` with an overloaded `operator&&`. When evaluating `left() && right()`, what happens if `left()` returns `Flag{false}`?

```cpp
struct Flag {
    bool ok;
    friend bool operator&&(Flag a, Flag b) { return a.ok && b.ok; }
};
Flag left();
Flag right();
bool r = left() && right();
```

A. `right()` is skipped due to short-circuit evaluation.
B. `right()` still executes because overloaded `operator&&` is a function call without short-circuiting.
C. `right()` may execute before `left()` because function arguments are unsequenced.
D. The program is ill-formed because overloading `operator&&` is forbidden since C++17.

**Answer (B):** `right()` still executes because overloaded `operator&&` is a function call without short-circuiting.

**Why:** Overloaded `operator&&` is dispatched as a regular function call, so both argument expressions (`left()` and `right()`) must be evaluated before the function body starts—short-circuiting is lost. Meanwhile, `[over.match.oper]/2` still sequences `left()` before `right()`.

### Question 4 [tricky] ([expr.call], [intro.execution])

In C++23, what is true about `consume(std::shared_ptr<Widget>(new Widget{1}), compute());` if `compute()` can throw?

```cpp
struct Widget { explicit Widget(int); };
int compute();
void consume(std::shared_ptr<Widget>, int);

consume(std::shared_ptr<Widget>(new Widget{1}), compute());
```

A. It can leak `Widget` if `compute()` runs between `new Widget{1}` and the `shared_ptr` constructor.
B. Argument 1 is guaranteed to finish before `compute()` is called.
C. `compute()` is guaranteed to run before `new Widget{1}`.
D. No leak occurs because argument evaluations cannot interleave, though `compute()` and argument 1 may run in either order.

**Answer (D):** No leak occurs because argument evaluations cannot interleave, though `compute()` and argument 1 may run in either order.

**Why:** Since C++17, function argument expressions are indeterminately sequenced rather than unsequenced (`[expr.call]/7`). Neither argument can interleave with the other—preventing the pre-C++17 leak—but the compiler may still evaluate argument 1 first or `compute()` first.

### Question 5 [standardese] ([expr.ass], [over.match.oper])

In C++23, what does `pick_lhs(a) = make_rhs();` print when `Target` defines `operator=`?

```cpp
struct Target {
    Target& operator=(const Target&) {
        std::cout << "assign ";
        return *this;
    }
};
Target& pick_lhs(Target& t) { std::cout << "lhs "; return t; }
Target make_rhs() { std::cout << "rhs "; return Target{}; }

Target a;
pick_lhs(a) = make_rhs();
```

A. `lhs rhs assign ` because member calls evaluate their left object before arguments.
B. `rhs lhs assign ` because operator-syntax assignment sequences the right operand before the left.
C. Either `lhs rhs assign ` or `rhs lhs assign ` because the order is unspecified.
D. Undefined behavior because `pick_lhs` and `make_rhs` are unsequenced.

**Answer (B):** `rhs lhs assign ` because operator-syntax assignment sequences the right operand before the left.

**Why:** In `[expr.ass]/1`, the right operand of an assignment is sequenced before the left operand. Under `[over.match.oper]/2`, expressions written with operator syntax (`pick_lhs(a) = make_rhs()`) preserve the built-in operator's operand sequencing rather than member-call order.

### Question 6 [standardese] ([expr.ass], [intro.execution])

Under C++23 rules, what is the behavior of `int i = 0; int v[2] = {10, 20}; v[i] = i++;`?

```cpp
int i = 0;
int v[2] = {10, 20};
v[i] = i++;
```

A. Well-defined: sets `v[1] = 0` and leaves `i == 1`.
B. Undefined behavior because `i` is modified and read unsequenced.
C. Well-defined: sets `v[0] = 0` and leaves `i == 1`.
D. Unspecified whether `v[0]` or `v[1]` receives `0`.

**Answer (A):** Well-defined: sets `v[1] = 0` and leaves `i == 1`.

**Why:** While `v[i] = i++;` was undefined behavior in C++14, C++17 `[expr.ass]/1` sequenced the right operand (`i++`, yielding `0` and incrementing `i` to `1`) completely before the left operand (`v[i]`). Thus `v[1]` is assigned `0` and `i` becomes `1`.
