AI InterviewSearch…Search problems, topics, or pages…Ctrl KGet started
Hardctype promotion

~105s

Comparing a signed value with an unsigned one

What does this C program print?

#include <stdio.h>

int main(void) {
    int a = -1;
    unsigned int b = 1;
    if (a < b) {
        printf("less");
    } else {
        printf("not less");
    }
    return 0;
}
Show the answer and the worked solution

Correct answer: B.

not less

Worked solution

  1. The usual arithmetic conversions turn the int into an unsigned int, because unsigned int has the same rank and wins the conversion.
  2. The bit pattern of -1 read as unsigned is the largest representable value, 4294967295 on a 32-bit int.
  3. 4294967295 < 1 is false, so the else branch runs and the program prints not less.

Answer: not less.

The idea

Mixing signed and unsigned in one comparison silently converts the signed side, so a negative number becomes enormous. Keeping loop counters and sizes on the same side of the signed divide avoids the whole class of bug.

Shortcut. When an int meets an unsigned int, the int converts: −1 becomes UINT_MAX, 4294967295 on 32 bits, which is not below 1.

Common trap. "less" reads the comparison as ordinary mathematics, −1 < 1, missing the silent conversion of a to unsigned.

Comparing a signed value with an unsigned one — Aptitude

Comparing a signed value with an unsigned one: What does this C program print? Answer and worked solution on CodeKairo.

Question

What does this C program print?

#include <stdio.h>

int main(void) {
    int a = -1;
    unsigned int b = 1;
    if (a < b) {
        printf("less");
    } else {
        printf("not less");
    }
    return 0;
}

Options

  1. less
  2. not less
  3. The program does not compile
  4. Nothing is printed
Show the answer and the worked solution

Correct answer: B. not less

Worked solution

  1. The usual arithmetic conversions turn the int into an unsigned int, because unsigned int has the same rank and wins the conversion.
  2. The bit pattern of -1 read as unsigned is the largest representable value, 4294967295 on a 32-bit int.
  3. 4294967295 < 1 is false, so the else branch runs and the program prints not less.

Answer: not less.

The idea

Mixing signed and unsigned in one comparison silently converts the signed side, so a negative number becomes enormous. Keeping loop counters and sizes on the same side of the signed divide avoids the whole class of bug.

Shortcut. When an int meets an unsigned int, the int converts: −1 becomes UINT_MAX, 4294967295 on 32 bits, which is not below 1.

Common trap. "less" reads the comparison as ordinary mathematics, −1 < 1, missing the silent conversion of a to unsigned.

All Programming Fundamentals questions · placement mock tests