I saw the following code in Computer Systems' book: "Programmer's Perspective," 2 / E. This works well and creates the desired result. The conclusion can be explained by the difference between signed and unsigned submissions.
#include<stdio.h> int main() { if (-1 < 0u) { printf("-1 < 0u\n"); } else { printf("-1 >= 0u\n"); } return 0; }
The above code gives -1 >= 0u , however the following code, which should be the same as above, does not work! In other words,
#include <stdio.h> int main() { unsigned short u = 0u; short x = -1; if (x < u) printf("-1 < 0u\n"); else printf("-1 >= 0u\n"); return 0; }
gives -1 < 0u . Why did this happen? I can not explain it.
Please note that I had the same questions as, but they do not help.
PS. As @Abhineet said, the dilemma can be solved by changing short to int . However, how to explain these phenomena? In other words, -1 in 4 bytes is 0xff ff ff ff , and in 2 bytes it is 0xff ff . Considering them as 2s-complement, which are interpreted as unsigned , they have corresponding values 4294967295 and 65535 . They are both not less than 0 , and I think that in both cases the output should be -1 >= 0u , i.e. x >= u .
Sample output for it on a small Intel system system:
In short:
-1 < 0u u = 00 00 x = ff ff
For int:
-1 >= 0u u = 00 00 00 00 x = ff ff ff ff
c bit-manipulation twos-complement unsigned-integer integer-promotion
Ali shakiba
source share