|
|
|
|
|
by MaxBarraclough
1283 days ago
|
|
Unfortunately abs(x-y) can overflow in two different ways. The subtraction can overflow, e.g. INT_MIN - 1, or 0 - INT_MIN. The abs
call can also overflow, with abs(INT_MIN). In both cases, the overflow causes
undefined behaviour. To calculate the difference between 2 signed integers we must bear in mind
that the result may exceed INT_MAX, and must use unsigned int for the result.
I wrote about this on StackOverflow: https://stackoverflow.com/q/10589559 |
|