Search code examples
c++coperator-precedencecomma-operator

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?


Solution

  • 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.