c - 当前的 C 标准是否禁止将 `&` 和 `|` 短路?

标签 c operators

C 标准中是否有任何内容(我猜目前是 C99 + TC1-3 C11 )保证 &|会不会短路?

如果我写:

x = y & foo();

...我预计 foo总是 被调用,但它真的被定义了吗?理论上,除非标准另有说明,否则如果 y 包含 0,则运行时优化可以在缺少不允许的情况下跳过调用。 (与 | 类似,如果左侧操作数已经全位开启,您可以忽略右侧操​​作数。就此而言,即使 x = y * foo(); 如果 y0,则可能被短路。)

不太了解规范(我也不知道),要证明这样的否定是很棘手的。我可以对比 &(C99 中的 6.5.10)和 &&(C99 中的 6.5.13)部分。在后者中,它非常清楚:

Unlike the bitwise binary & 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 equal to 0, the second operand is not evaluated.

...但是 6.5.10 没有具体说明它的否定版本。

在我看来,6.5.10 没有定义序列点这一事实似乎是合理的,这意味着 foo 将始终被调用,并且实现不会'调用它将是非标准的。我说得对吗?

最佳答案

It seems reasonable to me to take the fact that 6.5.10 doesn't define a sequence point to mean that foo will always get called and an implementation that didn't call it would be non-standard. Am I right about that?

是也不是。实际上,不会调用 foo 的实现将是非标准的。但是,它与序列点没有任何关系。

此处适用的段落为 5.1.2.3/3:

In the abstract machine, all expressions are evaluated as specified by the semantics. An actual implementation need not evaluate part of an expression if it can deduce that its value is not used and that no needed side effects are produced (including any caused by calling a function or accessing a volatile object).

关于c - 当前的 C 标准是否禁止将 `&` 和 `|` 短路?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9265492/

相关文章:

关于 c 中的 *(星号) 和++ 的混淆

C 字符数组初始化 : what happens if there are less characters in the string literal than the array size?

c - 多维数组的typedef?

我可以不断地malloc内存而不释放内存吗?

c# - 在 C# 中对 boolean 值使用 &=

ruby - 以下 ruby​​ 语法中的 `&` 是什么意思?

c - 为什么 argc 和 argv 的地址相差 12 个字节?

c - 为什么以下程序的输出是 2 97 而不是 2 2?

java - String new Object 和比较

python - 如何在Python中将字符串转换为日期运算符?