gpt4 book ai didi

c++ - C++ 中条件运算符中逗号运算符的优先级是多少?

转载 作者:可可西里 更新时间:2023-11-01 15:38:17 29 4
gpt4 key购买 nike

这里发生了什么?

#include <iostream>
using namespace std;

int main(){

int x=0,y=0;
true? ++x, ++y : --x, --y;
cout << "x: " << x << endl;
cout << "y: " << y << endl; //why does y=0 here?

x=0,y=0;
false ? ++x, ++y : --x, --y;
cout << "x: " << x << endl;
cout << "y: " << y << endl;
}

x: 1
y: 0

x: -1
y: -1

第二种情况似乎没问题。在第一种情况下,我希望 x 和 y 都递增到 1,但只有左侧操作数递增。

最佳答案

第一个相当于:

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

第二个相当于:

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

因此 --y 总是被执行。在第一行中,首先执行增量,因此 x = 1, y = 0 是预期的。在第二行中,首先执行 x 的递减,因此 x = -1, y = -1 是预期的。


Barmar 的评论(对另一个答案)所述:

And in case anyone is wondering why the comma between ++x and ++y doesn't have the same effect, it's because (true? ++x) would not be valid at all. So the compiler keeps scanning until it finds the :, but beyond that it stops when it reaches a lower precedence operator [(, in this example) or the end of statement].

关于c++ - C++ 中条件运算符中逗号运算符的优先级是多少?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12136156/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com