0

In every code piece I read online or on book, say if someone wants to compute the midpoint between s and e, they do:

int mid = s + ((e - s) / 2);

Mathematically isn't this the same thing as

int mid = (s + e) / 2;

So why is it written in the first way often? My guess is to prevent integer overflow but not sure.

Thanks

bZhang
  • 307
  • 1
  • 2
  • 12

1 Answers1

1

If e is close to the maximum value for an integer, then (s+e)/2 can overflow, but s+(e-s)/2 cannot (assuming that s is nonnegative).

For example (MAX_INT-2 + MAX_INT) == -4, so (MAX_INT-2 + MAX_INT)/2 == -2

Matt Timmermans
  • 53,709
  • 3
  • 46
  • 87