ProgrammingHardProduct company OA

In a binary search over int indices, why is mid = lo + (hi - lo) / 2 preferred to mid = (lo + hi) / 2?

  1. A. The first form rounds differently for negative indices
  2. B. The first form avoids a division, so it is faster
  3. C. lo + hi can exceed INT_MAX for large indices, and signed overflow is undefined behaviour
  4. D. The second form makes the loop run forever when lo equals hi

Correct answer: C. lo + hi can exceed INT_MAX for large indices, and signed overflow is undefined behaviour

Both give the same midpoint when nothing overflows, but lo + hi can overflow for indices above about INT_MAX / 2; hi − lo cannot, because it is never larger than hi. Both forms divide, and both handle lo == hi.

More C Programming questions

Exams that ask this topic