Question

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?

Was it helpful?

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.

OTHER TIPS

The relevant parts of the C++ grammar are:

conditional-expression:
    logical-or-expression
    logical-or-expression ? expression : assignment-expression
assignment-expression:
    conditional-expression
    logical-or-expression assignment-operator assignment-expression
    throw-expression
expression:
    assignment-expression
    expression, assignment-expression

In summary, while the 'middle' of a conditional expression can be a full expression extending up to the :, the last sub-expression can only be an assignment-expression which excludes expressions using the comma operator (other than where the comma operator appears as part of valid sub-expression of an assignment-expression such as a parenthesized primary-expression or as the second operand of another conditional-expression).

In C, the last sub-expression is more restricted, it cannot even be an assignment-expression although this is not a concern in your example.

conditional-expression:
    logical-OR-expression
    logical-OR-expression ? expression : conditional-expression

In this case

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

It is equivalent to

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

I guess it's because x ? y cannot be considered a valid expression, therefore the comma can't split the operator there. x ? y : z is a valid expression, the the comma after the colon can split into two expressions.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top