逗号运算符在C ++中的条件运算符的优先级是什么? [英] What's the precedence of comma operator inside conditional operator in C++?

查看:127
本文介绍了逗号运算符在C ++中的条件运算符的优先级是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这里发生了什么?

#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,但只有左手操作数增量。

The second case seems fine. I would expect both x and y to increment to 1 in the first case but only the left hand operand increments.

推荐答案

第一个等效于:

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

第二个等价于:

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

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

Thus the --y is always executed. In the first line, the increments are executed first so x = 1, y = 0 is expected. In the second line, the decrement of x is executed first so x = -1, y = -1 is expected.

Barmar


如果有人想知道为什么 ++ x ++ y 没有相同的效果,因为 x)根本不会有效。所以编译器保持扫描,直到它找到,但除​​此之外,当它到达较低优先级运算符 [(在此示例中)或语句结束]

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 ++中的条件运算符的优先级是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆