Friday, 23 March 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

casting - Why wasn&#39;t Tobey Maguire in The Amazing Spider-Man? - Movies &amp; TV

In the Spider-Man franchise, Tobey Maguire is an outstanding performer as a Spider-Man and also reprised his role in the sequels Spider-Man...