12

If one needs to compare int x with unsigned int y which is safer/better/nicer in C99 and with gcc 4.4+:

  1. (unsigned int)x == y
  2. x == (int)y

Does it matter?

3
  • It usually don't matter much, except in overflow situations (>= MAX_UINT/2, ie MAX_INT, ie 2**31 on 32 bits machines). Commented Nov 22, 2011 at 20:24
  • 3
    @BasileStarynkevitch: But this is about 50% of the possible values! What could matter more? Commented Nov 22, 2011 at 20:59
  • I agree, but with overflows the test don't really have natural sense... (and the test is still the same inside the machine). So it still don't matter... machine code is about the same... Commented Nov 22, 2011 at 21:16

2 Answers 2

17

Safest is to check that the number is in range before casting:

if (x >= 0 && ((unsigned int)x) == y)
8
  • Thanks, and is it OK to do (int)y when we're sure that y < INT_MAX/2? Commented Nov 22, 2011 at 20:19
  • Yes, it is ok, and probably faster to type (and to execute, when the compiler is not very optimizing) Commented Nov 22, 2011 at 20:23
  • You shouldn't do the cast and let the compiler chose. The rules for "usual arithmetic conversions" are a bit complicated but in essence there are architectures where the conversion would be to int and others where the conversion would be to unsigned, and for good reasons. Commented Nov 22, 2011 at 20:33
  • @James, you probably mean y < INT_MAX, no? Commented Nov 22, 2011 at 20:34
  • 1
    @Jens: Yes, I did, y < INT_MAX. Commented Nov 22, 2011 at 20:37
9

Yes, it does matter.

On a platform with 32bit int with e.g.

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

the expression x == y would yield 1 because through the "usual arithmetic conversions" the value of x is converted to unsigned and thus to 0xffffffff.

The expression (unsigned int)x == y is 1 as well. The only difference is that you do the conversion explicitly with a cast.

The expression x == (int)y will most likely be 1 as well because converting 0xffffffff to int yields -1 on most platforms (two's complement negatives). Strictly speaking this is implementation-defined behavior and thus might vary on different platforms.

Note that in none of the cases you will get the "expected" result 0. A good implementation is given in Mark Byers' answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.