ProgrammingVery hardTCS NQT · Infosys

What is printed? Assume signed char is 8 bits, two's complement.

What is printed? Assume signed char is 8 bits, two's complement.
#include <stdio.h>
#include <stdlib.h>
int cmp(const void *a, const void *b) {
    return *(const signed char *)a - *(const signed char *)b;
}
int main(void) {
    signed char v[] = {127, -56, 5};
    qsort(v, 3, sizeof v[0], cmp);
    for (int i = 0; i < 3; i++) printf("%d ", v[i]);
}
  1. A. -56 5 127
  2. B. 5 127 -56
  3. C. 127 5 -56
  4. D. -56 127 5

Correct answer: A. -56 5 127

The comparator subtracts two signed char values, and both promote to int before the subtraction, so the order is the signed order -56, 5, 127. Treating the bytes as unsigned would put -56 (the byte 200) last.

More C Programming questions

Exams that ask this topic