Search code examples
cintcomparetype-conversionunsigned-integer

Comparison between unsigned int and int without using cast operator


Everyone I looked around there exists a topic about my question yet I could not find.

unsigned int x = 5; 
int y = -3;
if(y<x)
   func1();
else
   func2();

func2 is called . But I want func1 called.

I know that I must use a cast operator when comparing these values.
But it is not allowed to use the cast operator or changing the type of a variable.

How can I solve this problem?


Solution

  • First check if y is a negative value, then knowing that, you know that x will always be bigger since it is unsigned.

    If y is not negative, then compare its value directly to x. I do not think this will cause an issue since there is no negative sign present.

    See the below example:

    if(y<0)
    {
        //x>y
        func1();
    }
    else if (y<x)
    {
        //lets say y=3, and x=5
        func1();
    }
    else
    {
        func2();
    }