C Programming Basics
int a = -1;
unsigned int b = 1;
if (a < b)
printf("a < b\n");
else
printf("a >= b\n");int and unsigned int are 32 bits. Which of the following is the result when the code above is executed?
- Aa < b is printed
- Ba >= b is printed
- CIt is a compile error, because signed and unsigned values cannot be compared
Show answer and explanation
Answer: B. a >= b is printed
When an int and an unsigned int are compared, both are first converted to unsigned int (the usual arithmetic conversions). As an unsigned int, −1 becomes 2³² − 1 = 4294967295, which is greater than 1, so a < b is false. Therefore "a >= b" is printed. With gcc, -Wextra (or -Wsign-compare) gives a warning for comparisons that mix signed and unsigned values.
- A. a is converted to unsigned int and becomes 4294967295, so it is not less than 1.
- B. Correct. −1 is converted to 4294967295 before the comparison.
- C. They can be compared; both are converted to unsigned int first.