An absolute difference would be the absolute value of the difference between 2 numbers. Suppose I have 2 int variables (x and y) and I would like to find the absolute difference. An easy solution would be:
unsigned diff = abs(x-y);
However these invoke undefined behavior and give incorrect results if overflow occurs such as if x is INT_MIN and y is INT_MAX. This returns 1 (assuming wraparound behavior) instead of UINT_MAX as expected.
Alright, the following works. @user16217248 got me started. See the discussion under that answer.
How to safely and efficiently find
abs((int)num1 - (int)num2)The secret is to do the
num1 > num2ternary comparison with signed integer values, but then to reinterpret cast them to unsigned integer values to allow for well-defined overflow and underflow behavior when getting the absolute value ofnum1 - num2.Here is my full test code:
absolute_value_of_num1_minus_num2.c from my eRCaGuy_hello_world repo:
Sample run and output:
Adjacently related
See also