what is the concept of evaluation of expression z = (y = 30) + (y = 10) + (y = 20); [closed]

Strictly speaking, the behavior is undefined:

6.5 Expressions

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. If there are multiple allowable orderings of the
subexpressions of an expression, the behavior is undefined if such an unsequenced side
effect occurs in any of the orderings.84)



84) This paragraph renders undefined statement expressions such as

   i = ++i + 1;
    a[i++] = i;

while allowing

   i = i + 1; 
    a[i] = i;

C 2011 Online Draft

Similar language exists for C++.

C does not force left-to-right evaluation of arithmetic expressions – each of the y=30, y=10, and y=20 subexpressions may be evaluated in any order (a parallel architecture may evaluate them all simultaneously). Each of these expressions has a side effect – they change the value of y:

6.5.16 Assignment operators

3    An assignment operator stores a value in the object designated by the left operand. An
assignment expression has the value of the left operand after the assignment,111) but is not
an lvalue. The type of an assignment expression is the type the left operand would have
after lvalue conversion. The side effect of updating the stored value of the left operand is
sequenced after the value computations of the left and right operands. The evaluations of
the operands are unsequenced.


111) The implementation is permitted to read the object to determine the value but is not required to, even
when the object has volatile-qualified type.

ibid.

Note that emphasized portion only specifies that the side effect is sequenced after evaluating the two operands – it doesn’t say that it occurs immediately after. y may be updated immediately after each assignment, or it might not.

“But”, I hear you say, “the result of y = 10 is 10 regardless of whether y is updated or not, so shouldn’t the value stored in z be 60 irrespective of all that other stuff?”

That’s the problem with undefined behavior – once any part of your program is undefined, the whole program is undefined. There are no guarantees of anything. z may get the value 60. It may get something else.

There’s no way of predicting what the value of y should be at the end of this, either.

Leave a Comment