我的印象是,在 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,因为
attr & 4 == 0
和(attr & 4) != 4
是1
因为attr & 4
code> 不等于4
。 (N1570 6.5.9 相等运算符)- 由于至少有一个操作数不为零,因此表达式的计算结果为
1
。 (N1570 6.5.14 逻辑或运算符) - 当控制表达式不为零时,
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/