2

I have written code like follow:

int a = -1;
unsigned int b = 0xffffffff;

if (a == b)
    printf("a == b\n");
else
    printf("a != b\n");

printf("a = %x b = %x\n", a, b);
return 0;

And the result is as follow:
enter image description here

It shows that a and b are equal. So I want to know how the computer make this judgement?

Himanshu
  • 4,327
  • 16
  • 31
  • 39
  • 1
    Are you asking how a computer does integer comparisons or how `-1` is the same as `0xffffffff` (in this case)? – OMGtechy Mar 08 '16 at 11:24
  • Possible duplicate of [Why the address number is not equal in dec and in hex?](http://stackoverflow.com/questions/16878650/why-the-address-number-is-not-equal-in-dec-and-in-hex) – Jongware Mar 08 '16 at 11:25
  • 1
    Take a look [HERE](http://stackoverflow.com/a/2085031/3436922) – LPs Mar 08 '16 at 11:26

2 Answers2

5

In any arithmetic operation with a signed integer a and unsigned integer b as operands, a will be implicitly cast to unsigned. Since -1 signed in this case is 0xffffffff unsigned, a and b compares equal.

Johann Gerell
  • 24,991
  • 10
  • 72
  • 122
1

The machine representation of your two values a and b is the same bit pattern (on your particular computer and implementation), so the a == b test is true.

BTW, you should enable all warnings and debug info when compiling (e.g. compile with gcc -Wall -Wextra -g if using GCC...). You'll probably get some warnings, because you probably has hit some undefined behavior. And you could run your code step by step in your debugger (e.g. gdb) and query the values (and their machine representations).

Basile Starynkevitch
  • 223,805
  • 18
  • 296
  • 547