而与所用逗号操作precedence? :运营商 [英] Comma operator precedence while used with ? : 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
然而,对于这些情况下,结果是相同的:
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屋!