【发布时间】:2025-12-24 16:15:11
【问题描述】:
我正在学习 C++,并在使用 , 和 ?: 运算符时偶然发现了以下行为。条件运算符的语法类似于E1 ? E2 : E3,其中 E1、E2 和 E3 是表达式 [1]、[2]。我从这段代码开始:
#include <iostream>
using namespace std;
int main(){
int x = 20, y = 25;
x > y ? cout << "x > y\n" , cout << "x is greater than y" : cout << "x !> y\n", cout << "x is not greater than y";
return 0;
}
和输出:
x !> y
x is not greater than y
这是我所期待的结果。但是当我将值更改为 int x = 25, y = 20 以使 x 大于 y 时,我得到以下输出:
x > y
x is greater than y
x is not greater than y
但我期待:
x > y
x is greater than y
因此,即使表达式 E1 的结果是 true,也会计算表达式 E3 的最后部分。
但是,当我将 E2 和 E3 放在括号内时,程序的输出在两种情况下都符合预期:当 x > y 和当 x , 是操作数 E1 和 E2 的 on 运算符,如 [1] 中的 E1, E2,它本身就是一个表达式。基于此,我不明白为什么 ?: 运算符的表达式 E3 的最后部分正在计算,即使表达式 E1 为真且两者兼而有之。
我的问题是:
1) 我是否正确使用了条件运算符?:?
2) 发生这种意外结果的机制是什么?
3) 为什么使用括号解决了问题(或者至少符合我的预期)?
我正在使用:gcc 版本 5.4.0 20160609 (Ubuntu 5.4.0-6ubuntu1~16.04.11)
非常感谢。
[1]https://en.cppreference.com/w/cpp/language/expressions
[2]https://en.cppreference.com/w/cpp/language/operator_other
【问题讨论】:
-
您可以在不使用逗号运算符的情况下输出两件事:
cout << one << two。这就是“流”运算符<<的设计方式。使用 this 是惯用的,所以它比添加括号更好。 -
带运算符优先级(或语法规则):
cond ? E1, E2 : E3, E4;等价于(cond ? (E1, E2) : E3), E4;。 -
@Fer 你得到的答案还不够吗?您的问题仍未解决。
标签: c++ conditional-statements operator-keyword comma