ProgrammingVery hardProduct company OA

An array of `int` that may contain any values from INT_MIN to INT_MAX is sorted with `qsort`. With `int x = *(const int *)a, y = *(const int *)b;`, which return statement gives a comparator that is correct for ALL inputs?

  1. A. return x - y;
  2. B. return x > y;
  3. C. return (x > y) - (x < y);
  4. D. return (unsigned)x - (unsigned)y;

Correct answer: C. return (x > y) - (x < y);

qsort needs a negative, zero or positive result that is a consistent total order. (x > y) − (x < y) yields exactly −1, 0 or 1 with no arithmetic on the values. x − y overflows (undefined behaviour) when the operands are far apart, e.g. INT_MIN − 1; in practice it wraps and reports the wrong sign. x > y never returns a negative value, so 'less' and 'equal' are indistinguishable and the order is inconsistent. The unsigned difference wraps modulo 2³² and its conversion back to int gives the wrong sign for the same far-apart pairs.

More C Programming questions

Exams that ask this topic