简体   繁体   中英

Sequence points and order of evaluation

I was reading through K&R and i came across this example about uncertainty in behavior while evaluating expression like a[i]=i++ ; The C99 spec in $6.5.2 says that

Between the previous and next sequence point an object shall have its stored value modified at most once by the evaluation of an expression. Furthermore, the prior value shall be read only to determine the value to be stored.

The above example from K&R holds good on the first statement. Please explain how does it fail on the second.

Does standard says anything about the order of evaluation of sub-expressions in case of the sequence points being involved. Eg. a[i++] || b[i++] a[i++] || b[i++] . I know that these are evaluated from left to right but how can this be derived from the above statement or is it explicitly stated in the standard somewhere ?

Does standard says anything about the order of evaluation of sub-expressions in case of the sequence points?

The order of evaluation is well defined in case of conditional operators && as well as || and that is the very reason short circuiting works.

It is explicitly specified by the c99 standard.

Reference: c99 Standard

Annex J: J.1 Unspecified behavior

1 The following are unspecified:
.....

The order in which subexpressions are evaluated and the order in which side effects take place, except as specified for the function-call (), &&, ||, ?:, and comma operators (6.5).
.....

Further in,
6.5.14 Logical OR operator

4) Unlike the bitwise | operator, the || operator guarantees left-to-right evaluation; there is a sequence point after the evaluation of the first operand. If the first operand compares unequal to 0, the second operand is not evaluated.

As well as for logical AND:

6.5.13 Logical AND operator

Unlike the bitwise binary & operator, the && operator guarantees left-to-right evaluation; if the second operand is evaluated, there is a sequence point between the evaluations of the first and second operands. If the first operand compares equal to 0, the second operand is not evaluated.

For the first part of the question:

The sentence applies to objects being changed by the expression, ie i (and a[i] ). So, the prior value of i shall be used exclusively to determine the "new" value for i .

But the expression "uses" it also to determine the array element to be written to.

The background is that otherwise it would be unclear if i denotes i 's value before or after the increment.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM