2

The following expression :-

int main()
{
    int x=2, y=9;
    cout << ( 1 ? ++x, ++y : --x, --y);
}

gives the following output:-

9

As per my understanding, it should return ++y which should be 10. What went wrong?

schwillr
  • 87
  • 6

2 Answers2

5

The ternary operator (? and :) has higher precedence compared to the comma operator (,). So, the expression inside the ternary conditional is evaluated first and then the statements are split up using the comma operator.

1 ? ++x, ++y : --x, --y

essentially becomes

   (1 ? (++x, ++y) : (--x)), (--y)
/* ^^^^^^^^^^^^^^^^^^^^^^^^ is evaluated first by the compiler due to higher position in
                            the C++ operator precedence table */

You can eliminate the problem by simply wrapping the expression in parentheses:

1 ? (++x, ++y) : (--x, --y)

This forces the compiler to evaluate the expression inside the parentheses first without any care for operator precedence.

Ruks
  • 3,886
  • 1
  • 10
  • 22
4

According to operator precedence,

1 ? ++x, ++y : --x, --y

is parsed as

(1 ? ++x, ++y : --x), --y

Jarod42
  • 203,559
  • 14
  • 181
  • 302
  • 2
    An explanation about [operator precedence](https://en.cppreference.com/w/cpp/language/operator_precedence) would be helpful here. – BoBTFish Jul 28 '21 at 13:27