Erdem ŞİMŞEK
Erdem ŞİMŞEK

Reputation: 33

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?

Upvotes: 3

Views: 1307

Answers (4)

chux
chux

Reputation: 153488

Use wider integer math for the compare. No cast used, type of variables are not changed.
An optimized compiler will not do a multiplication, just a integer widening.
Could use a * 1LL or + 0LL instead

int main(void) {
  long long ll = 1;
  unsigned int x = 5;
  int y = -3;
  // if (y < x)
  if (ll * y < ll * x)
    puts("func1();");
  else
    puts("func2();");
  return 0;
}

Output: func1();

long long is usually wider than int: See How to determine integer types that are twice the width as `int` and `unsigned`?

Upvotes: 0

Vlad from Moscow
Vlad from Moscow

Reputation: 310980

You can write the condition in the if statement the following way

if( y < 0 || y<x)
   func1();
else
   func2();

Upvotes: 2

venge
venge

Reputation: 187

Try complementing y (~y), it becomes 2

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

Upvotes: -1

Javia1492
Javia1492

Reputation: 892

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();
}

Upvotes: 3

Related Questions