ProgrammingHard

Which comparator for qsort on int array is correct for ALL int values (no overflow, no wrong sign)?

  1. A. return (x > y) - (x < y);
  2. B. return x - y;
  3. C. return x > y ? 1 : 0;
  4. D. return abs(x - y);

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

x - y can overflow for values near INT_MIN and INT_MAX, which is undefined. The comparison (x > y) - (x < y) yields -1, 0 or 1 without any arithmetic overflow, and a plain x > y never returns a negative value.

More C Programming questions

Exams that ask this topic