Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ operator "?:"

Tags:

c++

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?

like image 483
Pengcheng Avatar asked May 19 '15 05:05

Pengcheng


2 Answers

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!

like image 173
vsoftco Avatar answered Oct 06 '22 00:10

vsoftco


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;
}
like image 45
R Sahu Avatar answered Oct 05 '22 23:10

R Sahu