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.
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 ...
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With