Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comma operator precedence while used with ? : operator [duplicate]

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?

like image 930
Ali Avatar asked May 31 '13 09:05

Ali


1 Answers

This one:

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

is equivalent to:

((a > b) ? (a++, b--) : a--), 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.

like image 171
Jonathan Leffler Avatar answered Sep 19 '22 18:09

Jonathan Leffler