将逗号运算符与条件运算符一起使用

问题描述 投票:0回答:1

我正在学习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 ,的运算符为E1和E2,如E1, E2本身是一个表达式,而[1]则使用运算符E1和E2。基于此,我不理解为什么即使?:表达式为真且两者都为E1运算符计算表达式E3的最后部分。

我的问题是:

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

我正在学习C ++,并在使用和和?:运算符时偶然发现以下行为。条件运算符的语法类似于E1吗? E2:E3,其中E1,E2和E3是表达式[1],[2] ....

c++ conditional-statements operator-keyword comma
1个回答
-1
投票

有缺陷的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;
}
© www.soinside.com 2019 - 2024. All rights reserved.