schwillr
schwillr

Reputation: 87

c++ expression value (operator precedence)

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?

Upvotes: 2

Views: 155

Answers (2)

Ruks
Ruks

Reputation: 3956

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.

Upvotes: 5

Jarod42
Jarod42

Reputation: 217573

According to operator precedence,

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

is parsed as

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

Upvotes: 4

Related Questions