0

I am confused on the rules on the evaluation of the comma operator operands within a ternary conditional. Why are ++x, --a, and --b evaluated but not ++y?

#include <iostream>

int main()
{
    int x = 10;
    int y = 10;
    true ? ++x, ++y : --x, --y;
    std::cout << x << " " << y << std::endl; // output: 11 10

    int a = 10;
    int b = 10;
    false ? ++a, ++b : --a, --b;
    std::cout << a << " " << b << std::endl;   // output: 9 9
}

From https://en.cppreference.com/w/cpp/language/operator_precedence#cite_note-2 I can read: "The expression in the middle of the conditional operator (between ? and :) is parsed as if parenthesized: its precedence relative to ?: is ignored."

Can some one explain, why is y not incremented in the first conditional?

antero
  • 9
  • 2
  • Exact duplicate of: [Why does the ternary operator with commas evaluate only one expression in the true case?](https://stackoverflow.com/questions/47538906/why-does-the-ternary-operator-with-commas-evaluate-only-one-expression-in-the-tr) – Jason Sep 14 '22 at 09:04
  • There are cases where `if-else` is a lot easier to understand. – BoP Sep 14 '22 at 09:10

1 Answers1

2

It runs the ++y, but also the --y.

The line true ? ++x, ++y : --x, --y; is parsed as (true ? (++x, ++y) : --x), --y;. Only the --x is part of the false part of the ? operator, the --y is executed independently.

true ? ++x, ++y : (--x, --y);

will give you the expected result.

https://godbolt.org/z/3rrfMonh4

mch
  • 9,424
  • 2
  • 28
  • 42