Home > Enterprise >  Why the comparison result are not as expected?
Why the comparison result are not as expected?

Time:09-21

Could you explain why the following code give these result?

#include <iostream>
int main()
{
    int x = -1;
    unsigned int y = 1;
    if (x > y)
        std::cout << "true";
    else
        std::cout << "false";
}

Output = true but why ?

CodePudding user response:

What happens here is a implicit conversion from int to unsigned int, which happens to take place in the following manner.

int x = -a;
unsigned int y = x; //As far as y can hold only positive values, 
//it now holds UINT_MAX - (a   1)

Where UINT_MAX is a macro which is defined as the maximum value unsigned int can hold.

In your case x is converted to UINT_MAX, which is obviously larger than 1

CodePudding user response:

What happens here is that this code:

    int x = -1;
    unsigned int y = 1;

    bool result = x > y;

is converted to:

    int x = -1;
    unsigned int y = 1;

    bool result = operator>(x, y);

There are two operator> functions defined:

bool operator>(int, int);
bool operator>(unsigned int, unsigned int);

But you're calling operator>(int, unsigned int). So compiler has converted your signed int to unsigned int and then called operator>(unsigned int, unsigned int) which has resulted in a bug.

The standard way to avoid this is to turn on compiler warnings. You can use -Wconversion warning that will warn you about this specific issue, or even better pass -Wall to turn on all warnings.

To fix the bug in the code you can explicitly tell the compiler how to convert the arguments to the comparison operator

#include <iostream>
int main()
{
    int x = -1;
    unsigned int y = 1;
    if (x > static_cast<int>(y))
        std::cout << "true";
    else
        std::cout << "false";
}

But be careful with this as it can still result in a bug if your unsigned int is larger than the number that can fit into int. The safest solution is if you can make it so that both of the variables are the same type to begin with.

  • Related