4 ms·
Will this expression correctly handle overflow? size_t mid = (low + high) / 2;
by sobriquet9 6y ago
Will this expression correctly handle overflow?
size_t mid = (low + high) / 2;
- chrchang523 6y agoNot an issue since the following is at the top of the function: if (size + size < size) { return NULL; // size too big; avoid overflow }
- kt66 6y agowhat about low>>1 + high>>1 + (1 & low & high)
- nwallin 6y agoCareful about operator precedence. low>>1 + high>>1 + (1&low&high) is the same as low>>(1 + high>>(1 + (1&low&high)))
- mywittyname 6y agoInteresting question. Since this is integer division, I think you can do: size_t low_s = low >> 1; size_t high_s = high >> 1; size_t mid = (low_s + high_s) ...With no overflow worries. (expanded for clarity) That would effectively be distributing the division. So it's equivalent to low / 2 + high / 2.
- saagarjha 6y agoThis gives a different result when both low and high are odd.
- deleted 6y ago[deleted]