Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

got an unexpected answer from the x?y:z expression

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.

like image 437
cao lei Avatar asked May 18 '13 21:05

cao lei


1 Answers

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.

like image 190
perreal Avatar answered Oct 05 '22 15:10

perreal