c++ - 奇怪的 bool 转换(?)

标签 c++

请解释为什么第二个表达式返回 false

   cout << (4==4) << endl; //1
   cout << (4==4==4) << endl; // 0

最佳答案

(4==4==4) 基本上是 ((4==4)==4) 也就是 (true == 4) (1==4) 1false 2 被打印为0

请注意 == 具有关联性 left-to-right ,但这并不重要(在这种情况下),因为即使它具有从右到左的结合性,结果也会相同。


1。由于积分提升。
<补充>2。请注意,人们可能会想到 (true==4) 中的 4 可以被视为 true(毕竟 4 是非零的,因此 true)。这种想法可能会得出结论,(true==4)(true==true),即 true。但这不是它的工作原理。将 bool 提升为 int,而不是将 int 提升为 bool。

关于c++ - 奇怪的 bool 转换(?),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23940505/

相关文章:

C++ 不合格名称查找 : different structure size in different cpp's leading to operator new allocating less memory than constructor processes?

c++ - #ifdef x64 不适用于 Windows 资源文件

c++ fstream 在 1 个函数之后不起作用(通过引用)

c++ - 使用 3 维 vector 的问题

c++ - 在 C++ 中定义顶级空操作?

c++检查基引用的大多数派生类是否具有另一个基

c++ - 您使用过的最可靠、最快速的 Windows C++ 分析器是哪个?

c# - 绘制具有多个孔的多边形?

c++ - Luabridge 中出现 "addProperty"错误

c++ - `std::list<>::sort()` - 为什么突然切换到自上而下的策略?