Does relational operator in C have fixed evaluation order?

85 Views Asked by At

Here's the problem:

With int a,b,c;, is a = a * b + a; equivalent to (c = a * b)!=(a = c + a); with respect to modification of a?

At first glance I think they are the same, but then does specification say that in expr1 != expr2, expr1 will always be evaluated before expr2? I think it's not the case but I can't find a definitive source on this.

Also, I'm baffled by the what I found in http://en.cppreference.com/w/c/language/eval_order :

The side effect (modification of the left argument) of the direct assignment operator and of all compound assignment operators is sequenced after the value computation (but not the side effects) of both left and right arguments.

(since C11)

Does this mean I can interpret it as since C11 the above statement will have fixed evaluation order (since assignment is involved), but not pre-C11?

1

There are 1 best solutions below

0
On BEST ANSWER

(c = a * b)!=(a = c + a); invokes undefined behavior. The order of evaluation of expressions (c = a * b) and (a = c + a) is not sequenced.

C11-6.5/2:

If a side effect on a scalar object is unsequenced relative to either a different side effect on the same scalar object or a value computation using the value of the same scalar object, the behavior is undefined.[...]

The quotation

The side effect (modification of the left argument) of the direct assignment operator and of all compound assignment operators is sequenced after the value computation (but not the side effects) of both left and right arguments.

means that for the expressions like a = b; or a += b, assignment of b to a is sequenced after the evaluation of the subexpressions a and b in both statements. This is guaranteed by C standard. But, order of evaluation of a and b in the above statements is not guaranteed.