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?

4
  • unclear why you expect ++y as output. I could understand --y, but ++y is part of the condition not the output Commented Jul 28, 2021 at 13:28
  • Write it like this: (1 ? ++x, ++y : (--x, --y)). That ought to do what you're looking for. The grouping here is a bit peculiar, as the current answer indicates. Commented Jul 28, 2021 at 13:31
  • @463035818_is_not_a_number: OP expects 1 ? (++x, ++y) : (--x, --y)...
    – Jarod42
    Commented Jul 28, 2021 at 13:31
  • @Jarod42 oh well, I completely misread the conditional. Its a nice way to write unreadable code ;) Commented Jul 28, 2021 at 13:34

2 Answers 2

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.

4

According to operator precedence,

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

is parsed as

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

1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.