statquant statquant - 4 months ago 16
C++ Question

Why are multiple statements in ternary operator not executed

I am puzzled by the following:

#include <iostream>

int main()
{
bool a = true;
int nb = 1;
int nb2 = 2;
a ? nb++, nb2++ : nb--, nb2--;
std::cout << " (nb,nb2) = (" << nb << "," << nb2 << ")";
}


Result:

(nb,nb2) = (2,2)


Why is
nb2
not equal to
3
?

Answer

Because of operators priority. Your expression evaluates as

((a) ? (nb++, nb2++) : nb--), nb2--;

Operator , (comma) is the last thing to process. And this example would not compile at all but

The expression in the middle of the conditional operator (between ? and :) is parsed as if parenthesized.

See C++ Operator Precedence for details.

Comments