Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compare int and unsigned int

Tags:

c

gcc

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?

like image 653
Cartesius00 Avatar asked Nov 22 '11 20:11

Cartesius00


People also ask

What is the difference between int and unsigned int?

A signed integer is a 32-bit datum that encodes an integer in the range [-2147483648 to 2147483647]. An unsigned integer is a 32-bit datum that encodes a nonnegative integer in the range [0 to 4294967295]. The signed integer is represented in twos complement notation.

Can int and unsigned compare?

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.

How do you compare signed and unsigned integers?

A 1-byte unsigned integer has a range of 0 to 255. Compare this to the 1-byte signed integer range of -128 to 127. Both can store 256 different values, but signed integers use half of their range for negative numbers, whereas unsigned integers can store positive numbers that are twice as large.


2 Answers

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

if (x >= 0 && ((unsigned int)x) == y)
like image 132
Mark Byers Avatar answered Oct 02 '22 16:10

Mark Byers


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.

like image 22
undur_gongor Avatar answered Oct 02 '22 16:10

undur_gongor