문제

For C++03, the standard says, that between left and right operand of && operator there is a sequence point, so that all side effects of left operator have taken place before right operator is accessed.

So

int i = 0;
if (++i && i--)
    std::cout << i;

is well defined and is guaranteed to output 0.

But what is about this question: is right operand only evaluated if left operand is not 0? It seems to be a detail, but to me the standard guarantees only the sequence point between the operands, not that right operand is never evaluated/accessed in dependence of left one.

E.g.

int arr[10];
int pos; // somehow set to a value from 0 to 10
while (pos < 10 && arr[pos] != 0)
    pos++;

Is this well defined? pos could be from begin on 10 or reaches 10. The left operand has no side effects which concur with right operand. Have I the guarantee that arr[10] != 0 is never performed?

Edit:

Thanks to the comments and answers it is clear now:

5.14p2: "The result is a bool. If the second expression is evaluated,
every value computation and side effect associated with the first expression
is sequenced before every value computation and side effect associated with
the second expression."

is the sequence point meaning.

5.14p1: "Unlike &, && guarantees left-to-right evaluation: the second operand is
not evaluated if the first operand is false."

is the short-circuit meaning.

The first without the second would make my example undefined. Thanks.

도움이 되었습니까?

해결책 2

5.14p1 of C++11, last sentence:

Unlike &, && guarantees left-to-right evaluation: the second operand is not evaluated if the first operand is false.

So yes, it's guaranteed.

다른 팁

The standard does guarantee short-circuiting of && and ||.

If the left-hand side of && is false, the right-hand side is not evaluated. For ||, the right-hand side is not evaluated if the left-hand side is true.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top