Hacker News new | ask | show | jobs
by mredigonda 1290 days ago
You can also do x + (y - x) / 2 (starting point + distance halved), that doesn't overflow, is easy to remember, and the compiler would probably optimize it further.
6 comments

And wrong, since x=-1 and y=INT_MAX overflows.
Other comments point out that can overflow for some values.

However if you're doing mid-point in something like binary search where you already know y >= x AND x >= 0, then x + (y - x) / 2 is indeed a fine choice. It's a good one to remember.

This can overflow for signed integers.
Indeed this overflows too! Still don't have the rights here to edit or delete the comment, sorry for the confusion! It needs a couple of extra conditions: x and y need to be uint, and y needs to be >= x (you can swap them if they are not).
It's not a special right, you just have to do it within 2 hours.
The subtraction could overflow.
Why this could be better than (x+y)/2, since they both overflows?