C++Primer中一道关于运算符优先级的问题,为何交换了变量的顺序结果仍然一样?

#include <iostream>
using namespace std;
int main()
{
    int x = 0;
    int y = 0;
    int input = 0;
    
    cout << "Input a number:" << endl;
    cin >> input;

    input ? ++x, ++y : --x, --y;
    cout << "x = " << x << endl;
    cout << "y = " << y << endl;

    return 0;
}

如上代码输入1的话输出x=1,y=0

输入0的话输出x=-1,y=-1

奇怪的是把x和y交换位置输出结果一样,仍然是输入1输出x=1,y=0,输入0输出x=-1,y=-1

#include <iostream>
using namespace std;
int main()
{
    int x = 0;
    int y = 0;
    int input = 0;
    
    cout << "Input a number:" << endl;
    cin >> input;

    input ? ++y, ++x : --x, --y;
    cout << "x = " << x << endl;
    cout << "y = " << y << endl;

    return 0;
}
阅读 2k
3 个回答

++y, ++x++x, ++y是一样的啊,它们中间是,,不是;,属于一个语句,没毛病啊。

逗号运算符优先级最低,所以两种方式,分别相当于
(input ? ++x, ++y : --x), --y 和 (input ? ++y, ++x : --x), --y
所以结果当然也一样。

(input ? ++y, ++x : --x), --y;

这个--y是一定会执行的,看明白了吗?

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题