与逗号运算符优先使用? :operator [英] Comma operator precedence while used with ? : operator

查看:141
本文介绍了与逗号运算符优先使用? :operator的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不知道为什么下面两个子程序的结果是不同的:

I have no idea why the result of the two sub programs below are different:

    int a , b;

    a = 13, b=12;
    (a > b)? (a++,b--):(a--,b++); // Now a is 14 and b is 11

    a = 13, b=12;
    (a > b)? a++,b-- : a--,b++;   // Now a is 14 but b is 12

但是对于这些情况,结果是相同的: / p>

However for these cases, the results are identical:

    a = 13, b=12;
    (a < b) ? a++,b-- : a--,b++; // Now a is 12 and b is 13

    a = 13, b=12;
    (a < b) ? (a++,b--) : (a--,b++); // Again a is 12 and b is 13

为什么括号对,但对后的语句没有区别?

Why parentheses make difference for the statement after "?", but make no difference for the statement after ":"? Do you have any idea?

推荐答案

这一个:

(a > b)? a++,b-- : a--,b++; 

等效于:

((a > b) ? (a++, b--) : a--), b++;

所以 b 总是递增,递减。没有办法解析之间的逗号运算符,而不是等效于表达式中的括号。但是在之后,未加阴影的逗号终止三元?:运算符,并保持无条件执行增量。逗号运算符的优先级非常低,非常低。

so b is always incremented and only sometimes decremented. There is no way to parse the comma operator between ? and : other than as parenthesized in the 'equivalent to' expression. But after the :, the unparenthesized comma terminates the ternary ?: operator and leaves the increment as unconditionally executed. The precedence of the comma operator is very, very low.

这篇关于与逗号运算符优先使用? :operator的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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