Question about unsigned int in c

Possible duplicate:
unsigned int and signed char comparison

int j = 10;
unsigned int i = 10;
if( j > -1 )
    printf("1\n");
else
    printf("2\n");
if( i > -1 )
    printf("3\n");
else
    printf("4\n");

Conclusion:

1
4

I followed in the assembly, and the comparison is similar:

cmp     dword ptr [ebp-10h],0FFFFFFFFh
...
cmp     dword ptr [ebp-14h],0FFFFFFFFh

But still I don’t understand why one is true and the other is false.

IMO CPU has no idea whether it is signed dword ptror not.

So how does it work under the hood?

UPDATE

can anyone explain this at the assembly level?

+3
source share
7 answers

In the following code:

if( i > -1 )
    printf("3\n");
else
    printf("4\n");

-1 converts to unsigned int, which is the largest unsigned int and is clearly greater than 10.

On my machine, the following code

#include <stdio.h>
int main()
{
  unsigned int i = -1;
  printf("%u\n", i);
  return 0;
}

Productivity: 4294967295

+4
source

, -1 unsigned int. . "ja", "jg": .

+4

unsigned (i.e i) (i.e -1) unsigned.

-1 unsigned , ( i > -1) false.

[6.3.1.3/2] (C99)

, , , .

+2

, , :

  int j;
  unsigned int i;
  j = 10;
  i = (unsigned int)10;
  if (j > -1) { printf("1\n"); }
  else { printf("2\n"); }
  if (i > (unsigned int)-1) { printf("3\n"); }
  else { printf("4\n"); }

- int. - .

, , . , (, ,...).

+1

@Neil G , cmp unsigned vs signed, .

, (, sub) , , - .

, cmp - sub, .

+1

" > " , () . ( , "" ), -1 unsigned. -1 - , , 0xFFFFFFFF, , , 0x0000000A, ( , "-" ).

" " , , , , , .

0

When you compare unsigned int and signed int, the signed int is converted to unsigned int. Converting a negative signed int to an unsigned int is done by adding UINT_MAX + 1.

So -1 is converted to UINT_MAX + 1 - 1 = UINT_MAX, which is greater than 10.

See also What is the difference between the “no sign of conservation” and “save value” rules?

-1
source

All Articles