请解释输出:
#include<iostream.h>
int main()
{
int i= -3, j=2, k=0, m;
m = ++i || ++j && ++k;
cout<< i <<" " << j << " " << k <<" "<<m;
return 0;
}
输出:
-2 2 0 1
这是我的想法:
(++i ||++j) && (++k)//考虑优先顺序
++i 变成 -2 所以 OR 的第一部分为真,所以它不会检查第二部分。
(感谢 Joachim Pileborg 告诉我短路评估)
总的来说,AND 的第一部分是正确的。
但这还不足以使陈述为真,第二部分必须为真。
所以++k 使得 k = 1
这是我弄错的地方。为什么k不增加?
然而,在这种情况下:
#include<iostream.h>
int main()
{
int i= -1, j=2, k=0, m;
m = ++i || ++j && ++k;
cout<< i <<" " << j << " " << k <<" "<<m;
return 0;
}
输出:
0 3 1 1
考虑到短路评估,我也得到了这个。
让我们从这段代码开始
#include<iostream.h>
int main()
{
int i= -3, j=2, k=0, m;
m = ++i || ++j && ++k;
cout<< i <<" " << j << " " << k <<" "<<m;
return 0;
}
很明显,m
会将 bool 值转换为 int。由于 ++i
等于 -2,不等于零,因此不会计算所有其他表达式,因为已经知道整个表达式等于 true
。所以声明之后
m = ++i || ++j && ++k;
m
等于 1,i
等于 -2 所有其他变量均未更改。
在这段代码中
#include<iostream.h>
int main()
{
int i= -1, j=2, k=0, m;
m = ++i || ++j && ++k;
cout<< i <<" " << j << " " << k <<" "<<m;
return 0;
}
++i
将等于 0。因此 operator ||
的右操作数将被计算。这个操作数是
++j && ++k
由于 ++j
将等于 3 且不等于 0,因此 ++k
也将被计算并等于 1。因为两者operator &&
的操作数不等于零则结果等于true
因此你会得到 i == 0, j == 3, k == 1, m == 1。
来自 C++ 标准
5.14 逻辑与运算符
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.