为什么这个if语句结合赋值和相等性检查返回true? [英] Why does this if-statement combining assignment and an equality check return true?
问题描述
我一直在思考一些初学者的错误,最后我在 if
语句中找到了一个错误。我将代码扩展为:
I've been thinking of some beginner mistakes and I ended up with the one on the if
statement. I expanded a bit the code to this:
int i = 0;
if (i = 1 && i == 0) {
std::cout << i;
}
我已经看到 if
语句返回true,并且它 cout
的 i
为 1
。如果在if语句中为 i
分配了 1
,为什么 i == 0
返回 true
?
I have seen that the if
statement returns true, and it cout
's i
as 1
. If i
is assigned 1
in the if statement, why did i == 0
return true
?
推荐答案
具有运算符优先级。
if (i = 1 && i == 0)
不是
if ((i = 1) && (i == 0))
因为这两个& &
和 ==
的优先级高于 =
。真正的结果是
because both &&
and ==
have a higher precedence than =
. What it really works out to is
if (i = (1 && (i == 0)))
分配 1&& (i == 0)
到 i
。因此,如果 i
开始于 0
,则 i == 0
为 true
,因此 1&& true
是 true
(或 1
),然后是 i
设置为 1
。然后,由于 1
为true,因此输入if块并打印分配给 i
的值。
which assigns the result of 1 && (i == 0)
to i
. So, if i
starts at 0
then i == 0
is true
, so 1 && true
is true
(or 1
), and then i
gets set to 1
. Then since 1
is true, you enter the if block and print the value you assigned to i
.
这篇关于为什么这个if语句结合赋值和相等性检查返回true?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!