Sequence Points and Evaluation Order

I read through K & R and I came across this example about the uncertainty in behavior when evaluating an expression like a[i]=i++ ; The C99 spec at $ 6.5.2 says that

Between the previous and next points in the sequence, the object must have the changed value of the stored value no more than once by evaluating the expression. In addition, the previous value should only be read to determine the stored value.

The above example from K & R is good in the first statement. Please explain how this will happen during the second.

Does the standard know anything about how to evaluate subexpressions in the case of involved points in a sequence. For instance. a[i++] || b[i++] a[i++] || b[i++] . I know that they are evaluated from left to right, but how can this be obtained from the above statement or explicitly stated in the standard somewhere?

+4
source share
2 answers

Does the standard know anything about how to evaluate subexpressions in the case of sequence points?

The evaluation order is well defined in the case of conditional operators && , as well as || , and that is why working with a short circuit.

It is explicitly specified by the c99 standard.

Reference: c99 Standard

Appendix J: J.1 Undefined behavior

1 The following are unspecified:
.....

The order in which subexpressions are evaluated, and the order in which side effects occur, except as indicated for the calling function (), &, ||,?: And the comma of operators (6.5).
.....

Further,
6.5.14 The logical operator OR

4) Unlike bitwise | operator, || the operator guarantees an assessment from left to right; after evaluating the first operand, there is a point in the sequence. If the first operand is not equal to 0, the second operand is not evaluated.

As for logical AND:

6.5.13 The logical operator AND

Unlike bitwise binary code and operator, && operator guarantees evaluation from left to right; if the second operand is evaluated, then there is a sequence point between the estimates of the first and second operands. If the first operand is compared to 0, the second operand is not evaluated.

+4
source

In the first part of the question:

The sentence applies to objects that are modified by an expression, i.e. i (and a[i] ). Thus, the previous value of i should only be used to determine the β€œnew” value for i .

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

It is assumed that otherwise it would be unclear whether i means the value of i before or after the increment.

0
source

Source: https://habr.com/ru/post/1393699/


All Articles