序列点&&&运算符

Sequence point && operator

本文关键字:运算符      更新时间:2023-10-16

对于 c 03 ,标准称,&&操作员有一个序列点,因此在访问右操作员之前已经发生了左操作员的所有副作用。

so

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

定义很好,可以保证输出0

但是,这个问题是什么:正确操作数仅当左操作数不是 0时评估吗?这似乎是一个细节,但是对我而言,标准仅保证操作数之间的序列点, 从未对左一个依赖性进行评估/访问

,例如

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

这是定义的吗?pos可以是从10上开始的,也可以到达10。左操作数具有 no 副作用,与右操作数同意。我保证arr[10] != 0从未执行过吗?

编辑:

多亏了评论和答案,现在很明显:

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."

是序列点的含义。

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

是短路的含义。

第一个没有第二个会使我的示例不确定。谢谢。

标准确实保证了&&||的短路。

如果&&的左侧是false,则未评估右侧。对于||,如果左侧为true

,则未评估右侧

c 11的5.14p1,最后一句话:

与&amp;,&amp; amp;不同担保从左到右评估:如果第一操作数为false,则未评估第二操作数。

是的,可以保证。