Friday, March 23, 2018

c++ - Why are multiple statements in ternary operator not executed




I am puzzled by the following:



#include 

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.


No comments:

Post a Comment

plot explanation - Why did Peaches&#39; mom hang on the tree? - Movies &amp; TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...