struct Point { int x; int y; Point(int t_x, int t_y) { x = t_x; y = t_y; } }; int main() { Point lp(1,...">

C ++ operator "?:"

code:

#include <cstdio> struct Point { int x; int y; Point(int t_x, int t_y) { x = t_x; y = t_y; } }; int main() { Point lp(1, 4); Point rp(5, 0); int min_x, max_x, min_y, max_y; lp.x > rp.x ? max_x = lp.x, min_x = rp.x : max_x = rp.x, min_x = lp.x; lp.y > rp.y ? max_y = lp.y, min_y = rp.y : max_y = rp.y, min_y = lp.y; std::printf("min_x: %d max_x: %d\n", min_x, max_x); std::printf("min_y: %d max_y: %d\n", min_y, max_y); } 

I think:

 min_x=1 max_x=5 min_y=0 max_y=4 

But Real:

 min_x=1 max_x=5 min_y=4 max_y=4 

Why?

+5
source share
2 answers

The comma operator has the lowest precedence and is associated on the left. The next operator with the lowest priority in your expression is the ternary operator ?: , Which is associative from right to left. Therefore, your expression is evaluated as follows:

 ( (lp.y > rp.y) ? ( (max_y = lp.y), (min_y = rp.y) ): (max_y = rp.y) ), (min_y = lp.y); // The ?: ends here ^ 

So lp.y > rp.y ? YES. Set max_y = lp.y = 4 . Then evaluate the last one (min_y = lp.y) (the comma operator), so min_y = lp.y = 4 as well.

I really really hope this is an exercise, not a real code!

+17
source

Due to line operator priority

 lp.x > rp.x ? max_x = lp.x, min_x = rp.x : max_x = rp.x, min_x = lp.x; lp.y > rp.y ? max_y = lp.y, min_y = rp.y : max_y = rp.y, min_y = lp.y; 

equivalent to:

 (lp.x > rp.x ? (max_x = lp.x, min_x = rp.x) : max_x = rp.x), min_x = lp.x; (lp.y > rp.y ? (max_y = lp.y, min_y = rp.y) : max_y = rp.y), min_y = lp.y; 

min_x set to lp.x no matter what the values ​​are.
min_y set to lp.y no matter what the values ​​are.

You can easily and conveniently use your code using:

 int min_x, max_x, min_y, max_y; if ( lp.x > rp.x ) { max_x = lp.x; min_x = rp.x; } else { max_x = rp.x; min_x = lp.x; } 
+2
source

All Articles