为什么三元运算符返回 0?
Why is the ternary operator returning 0?
为什么以下代码输出“0”?
#include <bits/stdc++.h>
int main() {
int max = 5;
std::cout << (false) ? "impossible" : std::to_string(max);
}
声明
std::cout << false ? "impossible" : std::to_string(max);
相当于
(std::cout << false) ? "impossible" : std::to_string(max);
因为 <<
的优先级高于 ?:
并且 false
打印为 0
.
您可能已经预料到这一点
std::cout << (false ? "impossible" : std::to_string(max));
您应该阅读 operator precedence 以避免此类意外。
为什么以下代码输出“0”?
#include <bits/stdc++.h>
int main() {
int max = 5;
std::cout << (false) ? "impossible" : std::to_string(max);
}
声明
std::cout << false ? "impossible" : std::to_string(max);
相当于
(std::cout << false) ? "impossible" : std::to_string(max);
因为 <<
的优先级高于 ?:
并且 false
打印为 0
.
您可能已经预料到这一点
std::cout << (false ? "impossible" : std::to_string(max));
您应该阅读 operator precedence 以避免此类意外。