为什么三元运算符返回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));

您应该阅读运算符优先级以避免此类意外。


以上是为什么三元运算符返回0?的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>