hhb*_*lly 10 c++ comma operator-precedence
这里发生了什么事?
#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
Run Code Online (Sandbox Code Playgroud)
第二种情况似乎很好.我希望x和y在第一种情况下增加到1,但只有左手操作数增加.
Jon*_*ler 20
第一个相当于:
(true ? (++x, ++y) : (--x)), --y;
Run Code Online (Sandbox Code Playgroud)
第二个相当于:
(false ? (++x, ++y) : (--x)), --y;
Run Code Online (Sandbox Code Playgroud)
因此--y总是执行.在第一行中,首先执行增量,因此x = 1, y = 0是预期的.在第二行中,x首先执行减量,因此x = -1, y = -1是预期的.
如果有人想知道为什么逗号之间
++x和之间++y没有相同的效果,那是因为(true? ++x)根本不会有效.因此编译器会一直扫描直到找到它:,但除此之外,它会在到达较低优先级的运算符[(,在此示例中)或语句结束时停止).