Leo Heinsaar
Leo Heinsaar

Reputation: 4057

What will i++ + i++ evaluate to in C++17?

Looks like we're getting a whole new breed of "interview questions" for C++ (I hope not, actually).

It is known to be undefined behavior prior to C++17, but will it be well-defined from C++17 onward?

Since at the moment there doesn't seem to be a compiler that implements this C++17 modification, can anyone explain what will, according to expression evaluation rules, the value of x be in the following code?

int i = 0;
int x = i++ + i++;

Alisdair Meredith mentions this example here in his CppCon 2016 talk, but it's not entirely clear to me what the final value of x will be (although it seems what he's saying is that it'll be at least 1).

Obviously, i itself will in that case be 2 at the end of the expression.

Upvotes: 24

Views: 966

Answers (1)

Nicol Bolas
Nicol Bolas

Reputation: 474116

P0145R3 (PDF) does not change the evaluation order of all expressions. It only affects a small number of operators. And binary addition is not on that list.

Therefore the above code remains undefined.

Upvotes: 18

Related Questions