2 ms·
Signed integers may also have crazy high values so you're already on the hook for dealing with those. The case for unsigned values is that it frees you from hav
by ridiculous_fish 5y ago
Signed integers may also have crazy high values so you're already on the hook for dealing with those. The case for unsigned values is that it frees you from having to think about negative inputs. We all know to check for divide by zero; how many remember to check for INT_MIN / -1?
Regarding differences, in practice you usually want those differences to be non-negative. With uints, you compare first. Not:
int length = end - begin;
if (length < 0) return error;
but:
if (begin > end) return error;
unsigned length = end - begin;
This is also a good habit for signed ints, since it avoids underflow in more (but not all) cases.
An old post with a few fun crashes for negative inputs: https://kqueue.org/blog/2012/12/31/idiv-dos/ https://kqueue.org/blog/2012/12/31/idiv-dos/