Whenever I need to average two numbers for an algorithm like binary search, I always do something like this:
int mid = low + ((high - low) / 2);
<
The C++ version doesn't solve the overflow issue. It only solves the issue of successfully dividing by 2 using shift instead of /
, an optimization that your compiler should be able to make itself if it would be a performance improvement.
On the other hand overflow may not be a real problem, if your integral types are large enough to hold a reasonable range of indices.