Here is a simple C++ snippet:
int x1 = 10, x2 = 20, y1 = 132, y2 = 12, minx, miny, maxx, maxy; x1 <= x2 ? minx = x1, maxx = x2 : minx = x2, maxx = x1; y1 <= y2 ? miny = y1, maxy = y2 : miny = y2, maxy = y1; cout << "minx=" << minx << "\n"; cout << "maxx=" << maxx << "\n"; cout << "miny=" << miny << "\n"; cout <<" maxy=" << maxy << "\n";
I thought the result should be:
minx=10 maxx=20 miny=12 maxy=132
But actually the result is:
minx=10 maxx=10 miny=12 maxy=132
Could someone give an explanation why maxx
is not 20
? Thanks.
Due to operator precedence, expression is parsed like this:
(x1<=x2 ? minx=x1,maxx=x2 : minx=x2), maxx=x1;
you can solve this with:
(x1<=x2) ? (minx=x1,maxx=x2) : (minx=x2, maxx=x1);
And actually you don't need the first two pairs of parentheses. Also check this question.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With