I recently learned that integer overflow is an undefined behavior in C (side question - is it also UB in C++?)
Often in C programming you need to find the average of two
If you only have to deal with unsigned integer types (and can think in binary), you can decompose your addition into digit
and carry
. We can write a+b
(in unlimited precision) as (a^b) + ((a&b)<<1))
, so (a+b)/2
is simply ((a^b)>>1) + (a&b)
. This last expression fits within the common type of a
and b
, so you can use it in your code:
unsigned semisum(unsigned a, unsigned b)
{
return ((a^b)>>1) + (a&b);
}