ProgrammingVery hard

To sort 10^6 integers with qsort, which comparator is correct for all int values?

  1. A. static int cmp(const void *a, const void *b) { int x = *(const int *)a, y = *(const int *)b; return (x > y) - (x < y); }
  2. B. static int cmp(const void *a, const void *b) { return *(const int *)a - *(const int *)b; }
  3. C. static int cmp(const void *a, const void *b) { return *(const long *)a - *(const long *)b; }
  4. D. static int cmp(const void *a, const void *b) { return abs(*(const int *)a - *(const int *)b); }

Correct answer: A. static int cmp(const void *a, const void *b) { int x = *(const int *)a, y = *(const int *)b; return (x > y) - (x < y); }

The subtraction version overflows for large values of opposite sign, which is undefined. The boolean version never returns negative values, so qsort cannot order correctly.

More C Programming questions

Exams that ask this topic