1

I got here an actually "easy" C code Block but my compiler gives me an other result as expected.

int a;
int c;
unsigned int b;

a = b = 10;
c = -1;

if(a+b > c)
   printf("True\n");
else
   printf("False\n");

In my opinion a + b = 20 and its always more than -1 but why is it false?

  • 3
    `b` is unsigned. I think `a+b` then becomes an `unsigned` operation, and similarly the comparison is `unsigned`. You're comparing 20 with 65535. – lurker Jan 09 '20 at 14:09
  • other duplicates: [Comparison operation on unsigned and signed integers](https://stackoverflow.com/q/2084949/995714), [Why is a negative int greater than unsigned int? (duplicate)](https://stackoverflow.com/q/13600991/995714), [How is it possible for 0 <= -1 to return true? (duplicate)](https://stackoverflow.com/q/52309235/995714) – phuclv Jan 09 '20 at 14:24

2 Answers2

3

To be able to compare the result of a+b and c then they need to be the same type.

Because b is unsigned then the result of a + b is also unsigned. This means that either that result, or c, must be converted. The conversion will be that c is converted (through promotion) to an unsigned int and then -1 becomes a very large value (4294967295 on most systems). 20 > 4294967295 is false.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
1

The unsigned value of c is the largest value an integer can hold. Where as a signed value of c is -1. But if you print C as hexadecimal you receive 0xffffffff so it strictly comes to representation and consistency. -1 Can be treated as signed if you want it to be and unsigned if you don't want it to be. Try this code.

    int x = 0xffffffff;
    printf("%d",x);

It will print -1. So when comparing types you also have to be consistent of do you want the comparison and representation to be signed or unsigned? Your code can be fixed with a simple cast.

    int a;
    int c;
    unsigned int b;

    a = b = 10;
    c = -1;

    if((int)(a+b) > c)
       printf("True\n");
    else
       printf("False\n");
Irelia
  • 3,407
  • 2
  • 10
  • 31