奇怪的布尔转换(?) [英] Weird boolean conversion (?)
问题描述
解释pleasy为什么第二个表达式返回false
Explain pleasy why second expression returns false
cout << (4==4) << endl; //1
cout << (4==4==4) << endl; // 0
推荐答案
== 4 == 4)
基本上是((4 == 4)== 4)
这是 == 4)
这是(1 == 4)
1 / code> 2 这是打印为 0
。
(4==4==4)
is basically ((4==4)==4)
which is (true == 4)
which is (1==4)
1 which is false
2 which is getting printed as 0
.
==
具有关联性左对齐 - 右,但这并不重要(在 情况下),因为即使它具有从右到左的关联性,结果将是相同的。
Note that ==
has associativity left-to-right, but that doesn't matter (in this case) because even if it had associativity right-to-left, the result would have been the same.
1。由于整体推广。
2。请注意,有人可能会认为(true == 4)
中的 4
可以被视为 true
(毕竟 4
不是零,因此 true
)。这个想法可能会得出结论(true == 4)
是(true == true)
这是 true
。但这不是它的工作原理。它是bool,它被提升为int,而不是int到bool。
1. Due to integral promotion.
2. Note that one might tempted to think 4
in (true==4)
could be treated as true
(after all 4
is non-zero, hence true
). This thinking might conclude (true==4)
is (true==true)
which is true
. But that is not how it works. It is the bool which gets promoted to int, instead of int to bool.
这篇关于奇怪的布尔转换(?)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!