我正在学习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
所以即使表达式E3
的结果为E1
,也要计算表达式true
的最后部分。>>
但是,当我将E2和E3放在圆括号中时,对于两种情况,当x> y和x 我的问题是: 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_otherE1, E2
本身是一个表达式,而[1]则使用运算符E1和E2。基于此,我不理解为什么即使?:
表达式为真且两者都为E1
运算符计算表达式E3的最后部分。?:
?
我正在学习C ++,并在使用和和?:运算符时偶然发现以下行为。条件运算符的语法类似于E1吗? E2:E3,其中E1,E2和E3是表达式[1],[2] ....
有缺陷的c / c ++
#include <iostream>
using namespace std;
int main(){
int x = 20, y = 25;
cout << ( x > y ? "x > y\nx is greater than y" : "x !> y\nx is not greater than y") <<"\n";
return 0;
}