The operator +
only works for int
and larger. Thus when you use it with objects of type char
(which is smaller than int) these values are automatically converted to int before the operation happens.
Thus
abs((x1 + x2 + x3 + x4) - (x5 + x6 + x7 + x8)) / 4
Is converted by the compiler to:
abs((static_cast<int>(x1) + static_cast<int>(x2) + static_cast<int>(x3) + static_cast<int>(x4)) -
(static_cast<int>(x5) + static_cast<int>(x6) + static_cast<int>(x7) + static_cast<int>(x8))) / 4
So unless you are adding up a lot of char you are unlikely to overflow.
There is an issue assigning the result back to unsigned char
. If result of the expression is negative then you are going to have a conversion that makes the value positive (but well defined).