我很难理解以下代码的行为:
#include <stdio.h>
int main(void)
{
int i;
int j;
int k;
i = 7;
j = 8;
k = 9;
printf("%d\n", (i = j) || (j = k));
printf("%d, %d, %d\n", i, j, k);
return (0);
}
输出:
1
8, 8, 9
问题:
我了解expr1 | |如果 expr1 或 expr2(或两者)具有非零值,则 expr2 具有值 1。
i
的值从7
增加到8
,因为j
的值被分配给i
但同样的方式为什么j
的值没有增加,即使j = k?
我期待一个
输出
1
8, 9, 9
最佳答案
来自 C 标准(重点是我的):
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.
上述行为通常称为运算符(operator)短路。
在您的示例中,由于 (i = j)
不为零,因此不会评估第二个操作数。
关于c - 逻辑运算符 | |在 C 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68139943/