(I worked it out myself, asking a question - I thought it would be harder, and I would still welcome other answers if there are better ones!)
The unsigned integer solution is relatively simple (as described in Jack Thule's answer) and works by moving the (implied) conditional out of subtraction, so that we always subtract the smaller number from the larger one and don't compare the potentially wrapped value to zero:
if (a > b) return a - b; else return b - a;
This just leaves the question of integers. Consider the following variation:
if (a > b) return (unsigned) a - (unsigned) b; else return (unsigned) b - (unsigned) a;
We can easily prove that this works using modulo arithmetic. We know that a and (unsigned) a are congruent modulo UINT_MAX . In addition, an (unsigned) a - (unsigned) b operation corresponds to the actual subtraction modulo UINT_MAX , therefore, combining these facts, we know that (unsigned) a - (unsigned) b corresponds to the actual value a - b modulo UINT_MAX . Finally, since we know that the actual value of a - b must be between 0 and UINT_MAX-1 , we know that this is an exact equality.
source share