0

output is greater why??

#include <stdio.h> int main() { int i=-1; unsigned int j=1; if(i<j) printf("less"); else printf("greater"); return 0; }

22nd May 2019, 10:02 AM
Dee Pan Kar
Dee Pan Kar - avatar
3 odpowiedzi
0
In a signed integer type, part of this range is used to express negative numbers by some method. The sign-and-magnitude method uses the leftmost bit to signify if the integer is positive (0) or negative (1), with the rest of the bits telling how far from zero the integer is. therefore -1 can be written in binary as 101 where 1 stands for - sign and 01 stands for 1
22nd May 2019, 10:13 AM
Dee Pan Kar
Dee Pan Kar - avatar
0
Because j is unsigned, i is cast to unsigned as well in order to make the comparison; because -1 doesn't fit in an unsigned char, it overflows and becomes 255 (the bit-wise unsigned char equivalent of -1), which obviously is larger than 1. So comparison is if (255<1)
22nd May 2019, 10:16 AM
Prokopios Poulimenos
Prokopios Poulimenos - avatar
0
Your i (signed int) is promoted to an unsigned int for comparison. The binary of -1 is equivalent to 2**31-1 which is greater than 1 and thus you get greater. You can manually cast (int) on your unsigned int and you should get less
22nd May 2019, 10:22 AM
Paul