-1

In c programming why I am getting 0 zero for this? Why -5<(unsigned)5 is false?

main(){  
printf("%d",-5<(unsigned)5);  
getch();  
}
1
  • I think you have a typo in your program, at least if you want to print the result of the comparison. As it stands, your code will take a pointer to char ("%d"), subtract 5 (-5), try to compare the resulting pointer with integer 5, and then pass the result (an integer) to printf as if it were a pointer. On gcc this gives me an warning: passing argument 1 of 'printf' makes pointer from integer without a cast. Bottomline: you want to have a comma between the format string and the next argument.
    – Giorgio
    Nov 25, 2015 at 19:59

1 Answer 1

4

Because it's doing it as an unsigned comparison, which means it's actually checking if UINT_MAX - 4 < 5, which obviously is false.

IMO having no unsigned types is one of the few things Java really got right. It means you don't get headaches like this.

4
  • but i m also getting false when i type -5<unsigned(6)
    – tyt
    Nov 25, 2015 at 19:21
  • 1
    @tyt: Yeah, considering that UINT_MAX is over 4 billion, (assuming 32 bits as the default int size for your system,) that's to be expected. Nov 25, 2015 at 19:23
  • 6
    "IMO having no unsigned types is one of the few things Java really got right. It means you don't get headaches like this." . Seems like throwing the baby out with the bath water to me. Just because the designers of C couldn't be bothered defining sane comparisions between signed and unsigned types doesn't mean it can't be done. Nov 26, 2015 at 3:30
  • Well there are two different models (I'll call them modular and positive) and you need two types. C choose one (modular -- unsigned was introduced because people abused less restrictive rules and pointer arithmetic to get that behavior) and it is a pain when you want the other one. Ada choose the other and ended up by adding modular types to gather for the cases where the C choice is desirable. Nov 26, 2015 at 10:31

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