3

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?

chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256
  • http://stackoverflow.com/a/8233184/4185106 – moffeltje Jun 04 '15 at 13:35
  • If conversions warnings are enabled, the compiler should always generate one on such comparisons without explicit cast. Even if you check (y < 0) before the compare. So you will not get along without cast (and you should not!). That is actually how a cast should only be used: with full understanding about the problems. A coding style for C which _completely_ forbids typecasts but does not enforcing signed-ness warnings (and most/all other warnings) goes much too far. – too honest for this site Jun 04 '15 at 14:52

4 Answers4

3

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();
}
Javia1492
  • 862
  • 11
  • 28
2

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

if( y < 0 || y<x)
   func1();
else
   func2();
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
  • That would still generate a warning for the comparison. Sadly enough, coding styles disallow casts completely, but do not enforce warnings. Casts sometimes _do_ make sense sometimes. This example is actually a perfect proof. – too honest for this site Jun 04 '15 at 15:58
0

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`?

Community
  • 1
  • 1
chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256
-1

Try complementing y (~y), it becomes 2

unsigned int x = 5; 
int y = -3;
if(~y<x)
   func1();
else
   func2();
Iharob Al Asimi
  • 52,653
  • 6
  • 59
  • 97
venge
  • 177
  • 1
  • 9