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?

  1. Aa < b is printed
  2. Ba >= b is printed
  3. 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.
Practice this topic Back to topic

Books on C Programming Basics Ad

As an Amazon Associate I earn from qualifying purchases.

More C Programming Basics questions

  1. unsigned int is 32 bits. Which of the following describes the behavior when the code above is executed?
  2. A program that sets "char c = 200;" and prints c with %d in printf printed −56 when compiled and run with gcc for x86-64 Linux, and 200 with gcc for Arm Linux. Which of the following is the reason for the difference?
  3. Which of the following is the output when the code above, with b++ on the right side of && and ||, is executed?
  4. Which of the following is the output when the switch statement above, which contains a case without break, is executed?
  5. Which of the following is the output when the program above is executed?