这是代码:
void main()
{
clrscr();
int a=-3 , b=2 , c=0, d;
d = ++a && ++b || ++c;
printf("a=%d , b=%d , c=%d, d=%d ",a,b,c,d);
getch();
}
输出:-2 , 3 , 0 , 1
我无法理解为什么 c
的值没有递增,我想应该是1
d = 1
的输出是怎么来的? .
最佳答案
声明;
d = ++a && ++b || ++c;
从左到右分组(给定 precedence of &&
);
d = (++a && ++b) || ++c;
因此,在计算 &&
时,由于第一个操作数为 true(++a
),因此计算第二个操作数(++b
)。此时,这个逻辑与的结果是true
;因此,逻辑“或”为真,并且不计算第二个操作数(++c
)。
这种行为是有保证的,通常称为短路评估。 C++ 和 C 标准中的措辞是 listed here, in this answer ;此处针对 C++ 进行了简要复制;
§5.14 逻辑 AND 运算符
1 The
&&
operator groups left-to-right. The operands are both contextually converted to bool (Clause 4). The result is true if both operands are true and false otherwise. Unlike&
,&&
guarantees left-to-right evaluation: the second operand is not evaluated if the first operand is false.
§5.15 逻辑或运算符
1 The
||
operator groups left-to-right. The operands are both contextually converted to bool (Clause 4). It returns true if either of its operands is true, and false otherwise. Unlike|
,||
guarantees left-to-right evaluation; moreover, the second operand is not evaluated if the first operand evaluates to true.
关于c++ - 使用逻辑运算符时无法理解执行情况,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35941429/