c - 短路逻辑或行为

标签 c gcc clang

我的印象是,在 C 语言中,逻辑 OR 运算符 || 是一个短路运算符,如果 lhs 为假,则不会评估 rhs。我在比较“或”值时遇到了问题。有人可以向我解释为什么下面的代码(在 gcc 5.3 上)计算结果为 true 吗?我在 clang 中也遇到了同样的行为。

#include <stdio.h>

int main() {

    int attr = 2;

    if( ((attr & 2) != 2) || ((attr & 4) != 4) ) {
        printf("No short circuit?\n");
    };

    printf("%i %i\n",attr,(attr & 2));

};

输出:

No short circuit?

2 2

最佳答案

((attr & 2) != 2) || ((attr & 4) != 4) 计算结果为 true,因为

  1. attr & 4 == 0(attr & 4) != 41 因为 attr & 4 code> 不等于 4。 (N1570 6.5.9 相等运算符)
  2. 由于至少有一个操作数不为零,因此表达式的计算结果为 1。 (N1570 6.5.14 逻辑或运算符)
  3. 当控制表达式不为零时,if 语句执行第一个子语句(N1570 6.8.4.1 if 语句),您将其称为“计算结果为 true 的表达式”。

如果 lhs 为 true,逻辑 OR 运算符不会计算 rhs,因为在 rhs 为 true 或 false 的情况下,该值都为 true。

如果 lhs 为 false,逻辑 AND 运算符不会计算 rhs,因为在 rhs 为 true 或 false 的情况下,该值都将为 false。

引自N1570 :

6.5.13 Logical AND operator

[...]

3 The && operator shall yield 1 if both of its operands compare unequal to 0; otherwise, it yields 0. The result has type int.

4 Unlike the bitwise binary & operator, the && operator guarantees left-to-right evaluation; if the second operand is evaluated, there is a sequence point between the evaluations of the first and second operands. If the first operand compares equal to 0, the second operand is not evaluated.

6.5.14 Logical OR operator

[...]

3 The || operator shall yield 1 if either of its operands compare unequal to 0; otherwise, it yields 0. The result has type int.

4 Unlike the bitwise | operator, the || operator guarantees left-to-right evaluation; if the second operand is evaluated, there is a sequence point between the evaluations of the first and second operands. If the first operand compares unequal to 0, the second operand is not evaluated.

关于c - 短路逻辑或行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37233364/

相关文章:

c - 如何在DPDK代码中解释这段C代码

编译包含 ext2fs.h 的文件

c++ - LLVM:将全局变量链接类型设为 linkonce

在linux for windows上交叉编译不会输出DLL文件

c - 获取可执行文件中文本部分的开始和结束地址

c - 为什么我用 fscanf 读取第二行时得到一个空字符?

c - 使用类型 'struct s_action (*) 初始化类型 'enum Zahlen' 时出现类型不兼容错误

c - 编译大量代码生成的源文件的任何提示?

c++ - 我可以使用 LLVM 来加速构建并减少 GCC 编译时间吗?

c++ - `type *var = (int)0` ,合法与否?