ProgrammingHardGATE CS · Campus placements

A qsort comparator is written as return *(const int *)a - *(const int *)b; Which statement is true?

  1. A. It is correct for every pair of int values, because overflow always wraps
  2. B. It can invoke undefined behaviour when the subtraction overflows int, for example 2000000000 minus -2000000000
  3. C. It is always correct because qsort subtracts the values itself
  4. D. It fails only when the array holds unsigned values

Correct answer: B. It can invoke undefined behaviour when the subtraction overflows int, for example 2000000000 minus -2000000000

Signed int overflow is undefined behaviour, and the difference of two large-magnitude ints can exceed INT_MAX. Comparators should compare with < and > instead of subtracting.

More C Programming questions

Exams that ask this topic