Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 515
Erdem ŞİMŞEK Avatar asked Mar 01 '26 01:03

Erdem ŞİMŞEK


1 Answers

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();
}
like image 155
Javia1492 Avatar answered Mar 02 '26 14:03

Javia1492



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!