LearnFrenzy
Sign in Take a free test

Operators and Expressions · Find the Error · Question 4

Average of two large ints overflows Answer, explanation & discussion

  • Find the error
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 4 Back to Exercise

The program below has a bug. Which statement correctly describes it?

main.c
#include <stdio.h>

int average(int a, int b) {
    return (a + b) / 2;
}

int main(void) {
    printf("%d\n", average(2000000000, 2100000000));
    return 0;
}
  • A The division should be by 2.0
  • B a + b exceeds INT_MAX – signed overflow is undefined; use a + (b - a) / 2 or a wider type Correct
  • C average() must return long
  • D There is no bug
Correct Answer: Option B

4.1 × 10⁹ does not fit in a 32-bit int, so the addition overflows before the division (a sanitizer stops the program). Compute a + (b - a) / 2 or ((long long) a + b) / 2.

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