c++ - got an unexpected answer from the x?y:z expression -
here 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 result should be:
minx=10 maxx=20 miny=12 maxy=132
but result is:
minx=10 maxx=10 miny=12 maxy=132
could give explanation why maxx not 20? thanks.
due operator precedence, expression parsed this:
(x1<=x2 ? minx=x1,maxx=x2 : minx=x2), maxx=x1;
you can solve with:
(x1<=x2) ? (minx=x1,maxx=x2) : (minx=x2, maxx=x1);
and don't need first 2 pairs of parentheses. also check question.
Comments
Post a Comment