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?
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--xis part of the false part of the?operator, the--yis executed independently.will give you the expected result.
https://godbolt.org/z/3rrfMonh4