1. Home
  2. Computer Science MCQs
  3. C Programming
  4. A qsort comparator for int returns (a - b) and is used on…

Added 30 Nov -0001

A qsort comparator for int returns (a - b) and is used on values close to INT_MIN and INT_MAX. Why is this a defect?

  1. The comparator must return only 0 or 1, and any other return value is ignored by the qsort implementation
  2. Signed overflow in the subtraction is undefined behaviour, so the sign of the result can be wrong Correct answer
  3. qsort requires the comparator to return a long rather than an int, so the subtraction must be widened
  4. qsort calls the comparator once per element, so ties between equal keys are never detected at all

Correct answer

B. Signed overflow in the subtraction is undefined behaviour, so the sign of the result can be wrong

14 views

MCQSEXAM

Explanation

Overflow-safe comparison is required because INT_MAX minus INT_MIN cannot be represented in int, and signed overflow is undefined behaviour that can invert the ordering. The portable form is (a > b) - (a

Reference

Asked in: NTS, PPSC IT, Campus Interviews

Preparing for an exam?

Doubts & discussion

Not sure why the answer is B? Ask here and get an explanation.

Ask a doubt about this MCQ

Shown after review. No links please.

More C Programming MCQs

Practise all C Programming MCQs

Similar MCQs