How can one prevent overflow when calculating the absolute of the difference of two unsigned integers?
The result must be an unsigned integer as well (actually independent of the processer, as it will mathematically be just a number between 0 and MAXINT).
unsigned int a;
unsigned int b;
abs(a-b);
But this only works if b<=a, otherwise a-b<0 and will then overflow, and taking abs
later will not help.
What is the easiest, overflow-safe way of doing that calculation?
(Actually I want to test if |a-b|<c where c is some constant. So, one could check a-bb and b-aa.)
Thanks to the answers in the comments, one sees a simple solution can be accomplished like that using case differentiation.