top | item 33893236

(no title)

mredigonda | 3 years 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.

discuss

order

planede|3 years ago

And wrong, since x=-1 and y=INT_MAX overflows.

jlokier|3 years ago

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.

orlp|3 years ago

This can overflow for signed integers.

mredigonda|3 years ago

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).

mkl|3 years ago

It's not a special right, you just have to do it within 2 hours.

phkahler|3 years ago

The subtraction could overflow.

fyresala|3 years ago

Why this could be better than (x+y)/2, since they both overflows?