skip to content

Since C++17, why does `std::cout << cur.next() << cur.next()` read bytes in order while `make_header(cur.next(), cur.next())` may not?

level: seniorimportance: should knowfreq 48%

answer

  1. P0145, refining evaluation order
  2. shift operands now left to right
  3. assignment: right side first
  4. arguments indeterminately sequenced

basics

~20 s

C++17 sequences the left operand of << before the right one, also for overloaded stream operators, so the chain reads left to right. Function arguments are only indeterminately sequenced: they never interleave, but either may run first.

solid answer

~40 s

C++17 (paper P0145R3) added order guarantees to operators people chain: for `a << b` and `a >> b`, `a` is sequenced before `b`; for `a = b` the right operand is sequenced before the left; for `a[b]` and `a.*b`, `a` comes first; and the function expression is sequenced before its arguments. Overloaded operators keep the built-in order, so a `std::cout <<` chain reads `cur.next()` left to right. Function arguments, though, are still indeterminately sequenced with each other: no interleaving, but no fixed order, so `make_header` may receive the bytes swapped. C++17 also made `i = i++ + 1` well-defined, while `i++ + i` remains undefined. Read fields into named locals when order matters.

code

cpp · 27 lines
cpp
#include <cstdint>
#include <iostream>
#include <map>
#include <string>

struct Cursor {
    const std::uint8_t* p;
    std::uint8_t next() { return *p++; }
};

void make_header(int version, int flags) {
    std::cout << "version=" << version << " flags=" << flags << '\n';
}

int main() {
    const std::uint8_t bytes[] = {4, 0x12};

    Cursor c1{bytes};
    std::cout << int(c1.next()) << ' ' << int(c1.next()) << '\n';  // C++17: 4 18

    Cursor c2{bytes};
    make_header(c2.next(), c2.next());   // argument order unspecified

    std::map<std::string, std::size_t> ids;
    ids["ack"] = ids.size();             // C++17: right side first, stores 0
    std::cout << "ack=" << ids["ack"] << '\n';
}

go deeper

for a junior

Recall that C++ does not promise left-to-right evaluation of function arguments, and that a << chain reads left to right since C++17.

for a middle

Explain sequenced-before, indeterminately sequenced and unsequenced, and which operators C++17 gave a fixed order.

for a senior

Spot order-dependent reads in parsers and constructors, explain why one compiler's output proves nothing, and fix them with named locals.

for a principal

Decide whether the codebase may rely on C++17 ordering at all, given every target's -std level, and encode the answer in review rules.

## Sequenced before, unsequenced, indeterminately sequenced The C++ standard describes evaluation order with three relations between two evaluations A and B on one thread: - **sequenced before**: A completes (value and side effects) before B starts; - **indeterminately sequenced**: one runs entirely before the other, but which one is unspecified; - **unsequenced**: no order at all, and the two may even overlap. The default, in the draft's words, is that "evaluations of operands of individual operators and of subexpressions of individual expressions are unsequenced". If a side effect on a memory location is unsequenced relative to another side effect on, or a read of, the same location, the behaviour is undefined. That is why `i++ + i` has no defined result. ## What C++17 tightened C++17 adopted paper P0145R3, "Refining expression evaluation order", which added sequencing for operators that idiomatic C++ chains: | Expression | Rule since C++17 | |---|---| | `a << b`, `a >> b` | `a` sequenced before `b` | | `a = b`, `a += b`, ... | right operand `b` sequenced before left operand `a` | | `a[b]` | `a` sequenced before `b` | | `a.*b`, `a->*b` | `a` sequenced before `b` | | `f(args)` | the function expression `f` (including `obj.f`) sequenced before every argument | Overloaded operators follow the same order: since C++17, when operator notation picks a user-declared function, "the operands are sequenced in the order prescribed for the built-in operator". So a stream chain `std::cout << cur.next() << cur.next()` reads the two bytes left to right. ## What C++17 left unspecified **Function arguments still have no order.** The draft says the initialization of each parameter "is indeterminately sequenced with respect to that of any other parameter". In `make_header(cur.next(), cur.next())` the two calls do not interleave, but either may run first, so the version and the flags can arrive swapped. Before C++17 the argument evaluations were unsequenced, so `f(i++, i++)` was undefined; since C++17 it is only unspecified which argument sees which value. Operands of most other operators also remain unsequenced: in `read() + read()` or `a() & b()` either side may go first. ## Puzzles an interviewer uses Each line below assumes `int i = 1;`: 1. `i = i++ + 1;` was undefined before C++17; since C++17 the right operand, including the increment's side effect, is sequenced before the assignment, and `i` ends as `2`. The draft lists this exact line as "the value of i is incremented". 2. `i = i++ + i;` is still undefined: inside the right operand, the increment and the second read of `i` are unsequenced. 3. `ids[key] = ids.size();` on a `std::map` stores the size measured **before** `operator[]` inserts `key`, because the right operand is evaluated first. 4. `v[i] = i++;` is defined since C++17: `i++` runs first, then `v[i]` indexes with the incremented `i`. Clang shows the change directly: compiled as C++14, `i = i++ + 1` draws "multiple unsequenced modifications to 'i' [-Wunsequenced]"; as C++17 the warning disappears, while `j++ + j` is still flagged under both. ## Why the committee changed it The rules before C++17 made ordinary-looking C++ unreliable. A chain such as `s.replace(s.find("a"), 1, "b").replace(s.find("c"), 1, "d")` could run the second `find` before the first `replace` had modified the string, so it searched stale text; a stream chain `std::cout << f() << g()` could call `g()` first; and `m[k] = m.size()` could insert before or after measuring. Each of these reads naturally from left to right, and P0145R3 made the language agree with that reading for the operators where idiomatic code chains calls. Function arguments were left in an unspecified order; the companion paper adopted at the same meeting, P0400R0, only ruled out interleaving them. ## How to write code that does not care - Read sequential fields into named locals, one statement each, then call the constructor: `auto ver = cur.next(); auto flags = cur.next(); make_header(ver, flags);`. - Never modify a variable twice, or modify and read it, inside one expression unless an operator listed above orders the two. - Do not rely on one compiler's argument order: Apple clang 21 evaluated `make_header`'s arguments left to right in the example below, and the standard allows the opposite. Why unsequenced modification is undefined behaviour, and what optimizers do with it, belongs to the material on classic sources of undefined behaviour; this question is about which orders the language now guarantees.

  • What does `ids[key] = ids.size();` store for a new key in a `std::map`, before and after C++17?
    Since C++17 the right operand of `=` is sequenced before the left, so `size()` is taken before `operator[]` inserts the key and the stored value is the old size. Before C++17 the two operands had no required order, so either call could run first and the stored value could be the old size or the new one.
  • Is `f(i++, i++)` undefined behaviour in C++17?
    No longer. Before C++17 argument evaluations were unsequenced, so two modifications of `i` made it undefined. C++17 makes parameter initializations indeterminately sequenced, so the two increments cannot overlap; which argument receives the smaller value is unspecified. It is still unreadable code and should be split.
  • Does C++17 make `a.f(x()).g(y())` evaluate `x()` before `y()`?
    Yes. The postfix expression naming the function, here `a.f(x()).g`, is sequenced before the call's arguments, and evaluating that postfix expression includes the call to `f` and therefore `x()`. So `x()` and `f` complete before `y()` starts, which fixed the classic chained `replace(find(...))` bug.

  • C++17 made all function arguments evaluate left to right.
  • In C++17 i = i++ + i is well-defined, like i = i++ + 1.
  • Overloaded stream operators are just function calls, so their operands have no order.
  • Argument order is defined by the calling convention, so it is portable.
  • If one compiler evaluates arguments left to right, the code is correct.

Assumes C++17 or later; P0145R3 added the shift, assignment, subscript and call-expression orders, which were unsequenced or unspecified before C++17.