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.
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.
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).
planede|3 years ago
jlokier|3 years ago
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.
orlp|3 years ago
mredigonda|3 years ago
mkl|3 years ago
unknown|3 years ago
[deleted]
phkahler|3 years ago
fyresala|3 years ago