而与所用逗号操作precedence? :运营商 [英] Comma operator precedence while used with ? : operator

查看:154
本文介绍了而与所用逗号操作precedence? :运营商的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

然而,对于这些情况下,结果是相同的:

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 总是递增,只是有时递减。有没有办法来解析之间的逗号操作符 不是括号中的'等同于'恩等pression。但经过中,逗号加括号终止三元运营商和叶为无条件执行的增量。逗号操作符的precedence是非常,非常低。

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.

这篇关于而与所用逗号操作precedence? :运营商的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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