iamOgunyinka
iamOgunyinka

Reputation: 1050

Sequence Point and Evaluation Order( Preincrement)

There was a debate today among some of my colleagues and I wanted to clarify it. It is about the evaluation order and the sequence point in an expression. It is clearly stated in the standard that C/C++ does not have a left-to-right evaluation in an expression unlike languages like Java which is guaranteed to have a sequencial left-to-right order. So, in the below expression, the evaluation of the leftmost operand(B) in the binary operation is sequenced before the evaluation of the rightmost operand(C):

A = B B_OP C

The following expression according, to CPPReference under the subsection Sequenced-before rules(Undefined Behaviour) and Bjarne's TCPPL 3rd ed, is an UB

x = x++ + 1;

It could be interpreted as the compilers like BUT the expression below is said to be clearly a well defined behaviour in C++11

x = ++x + 1;

So, if the above expression is well defined, what is the "fate" of this?

array[x] = ++x;

It seems the evaluation of a post-increment and post-decrement is not defined but the pre-increment and the pre-decrement is defined.

NOTE: This is not used in a real-life code. Clang 3.4 and GCC 4.8 clearly warns about both the pre- and post-increment sequence point.

Upvotes: 0

Views: 207

Answers (2)

ecatmur
ecatmur

Reputation: 157534

In array[x] = ++x;, there are two value computations on the scalar object x, and one side effect on x.

The value computation of ++x is sequenced relative to its side effect, but the value computation of x in array[x] is not sequenced relative to the side effect of ++x.

So the behavior is undefined.

The difference between x = ++x and array[x] = ++x is that in the former the appearance of x on the LHS is subject to side effect, while in the latter the x on the LHS is subject to value computation.

Upvotes: 0

Mike Seymour
Mike Seymour

Reputation: 254771

Lets see what the standard says about sequencing:

C++11 5.17/1: the assignment is sequenced after the value computation of the right and left operands, and before the value computation of the assignment expression.

So the evaluation of the operands array[x] and ++x are not sequenced with respect to each other. Both use the value of x, and one modifies it, giving undefined behaviour.

(The second example differs by not using the value of x in the left operand; it remains an lvalue).

Upvotes: 5

Related Questions