3

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.

4

2 に答える 2

8

&&規格では、との短絡が保証されてい||ます。

の左辺が の場合&&false右辺は評価されません。の場合||、左側が の場合、右側は評価されませんtrue

于 2014-01-20T16:16:32.440 に答える
5

C++11 の 5.14p1、最後の文:

& とは異なり、&& は左から右への評価を保証します。最初のオペランドが false の場合、2 番目のオペランドは評価されません。

そうです、それは保証されています。

于 2014-01-20T16:17:07.897 に答える