Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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.

like image 546
Lmn Avatar asked Sep 30 '16 17:09

Lmn


People also ask

Does C evaluate left to right?

There is no concept of left-to-right or right-to-left evaluation in C, which is not to be confused with left-to-right and right-to-left associativity of operators: the expression f1() + f2() + f3() is parsed as (f1() + f2()) + f3() due to left-to-right associativity of operator+, but the function call to f3 may be ...

What is C evaluation?

Expression evaluation in C is used to determine the order of the operators to calculate the accurate output. Arithmetic, Relational, Logical, and Conditional are expression evaluations in C.

How do you evaluate an expression in C++?

In the C++ programming language, an expression is evaluated based on the operator precedence and associativity. When there are multiple operators in an expression, they are evaluated according to their precedence and associativity.


Video Answer


1 Answers

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.

like image 148
Nicol Bolas Avatar answered Sep 17 '22 13:09

Nicol Bolas