【问题标题】:Why is the ternary operator returning 0?为什么三元运算符返回0?
【发布时间】:2021-04-28 17:51:28
【问题描述】:

为什么下面的代码输出为 '0'?

#include <bits/stdc++.h>

int main() {
    int max = 5;
    std::cout << (false) ? "impossible" : std::to_string(max);
}

【问题讨论】:

  • 因为false 打印为0。该语句等效于(std::cout &lt;&lt; false) ? "impossible" : std::to_string(max);。你可能想要std::cout &lt;&lt; (false ? "impossible" : std::to_string(max));

标签: c++ c++11 conditional-operator


【解决方案1】:

声明

std::cout << false ? "impossible" : std::to_string(max);

等价于

(std::cout << false) ? "impossible" : std::to_string(max);

因为&lt;&lt; 的优先级高于?: 并且false 打印为0

你可能已经预料到了

std::cout << (false ? "impossible" : std::to_string(max));

您应该阅读operator precedence 以避免此类意外。

【讨论】:

  • 运算符优先级:* 绑定比+.-&gt; 比两者都紧,分配非常松散,其他一切都使用()
  • 简而言之:“如有疑问,请使用括号。”
  • @Swift-FridayPie 这还不够,因为这个问题表明你甚至不清楚什么时候应该有疑问 :-)
  • @BartoszKP 不只是 *、/、+、- 和 =,因为代数是较小的公分母
猜你喜欢
  • 2014-08-03
  • 2015-08-20
  • 2014-12-18
  • 2019-07-08
  • 2016-05-15
  • 1970-01-01
  • 2020-12-07
  • 1970-01-01
相关资源
最近更新 更多