为什么三元运算符返回 0?

Ji *_*i W 0 c++ conditional-operator c++11

为什么以下代码的输出为“0”?

#include <bits/stdc++.h>

int main() {
    int max = 5;
    std::cout << (false) ? "impossible" : std::to_string(max);
}
Run Code Online (Sandbox Code Playgroud)

Tho*_*lik 5

该声明

std::cout << false ? "impossible" : std::to_string(max);
Run Code Online (Sandbox Code Playgroud)

相当于

(std::cout << false) ? "impossible" : std::to_string(max);
Run Code Online (Sandbox Code Playgroud)

因为<<具有更高的优先级?:并且false被打印为0.

你可能已经预料到了

std::cout << (false ? "impossible" : std::to_string(max));
Run Code Online (Sandbox Code Playgroud)

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