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?
The comma operator has the lowest precedence, and is left-to-right associative. The next lowest precedence operator in your expression is the ?:
ternary operator, which is right-to-left associative. Hence your expression evaluates to:
( (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 (min_y = lp.y)
(comma operator), so min_y = lp.y = 4
also.
I really really hope this is an exercise and not actual code though!
Due to operator precedence, the lines
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;
are 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
is set to lp.x
no matter what the values are.min_y
is set to lp.y
no matter what the values are.
You can make your code easy to follow and maintain by 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;
}
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