LearnFrenzy
Sign in Take a free test

Operators and Expressions · Operators MCQ · Question 11

Overflow-safe average of two ints in C Answer, explanation & discussion

  • MCQ
  • Hard
  • 0 comments
  • Answer explained
  • Moderated community
Question 11 Back to Exercise

Which expression computes the midpoint of two large non-negative ints lo ≤ hi without overflow?

  • A (lo + hi) / 2
  • B lo + (hi - lo) / 2 Correct
  • C lo / 2 + hi
  • D (lo * hi) / 2
Correct Answer: Option B

lo + hi can exceed INT_MAX (signed overflow is undefined). hi - lo always fits, so lo + (hi - lo) / 2 is safe – a famous bug once found in Java's binary search.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links