Reboot Your Dreamliner Every 248 Days To Avoid Integer Overflow

However if you're trying to model a non-negative number using an unsigned int the your model immediately falls apart as soon as you involve subtraction as it doesn't behave the same way since you will always end up with positive durations and distances.

This makes no sense. Every single integer type, whether unsigned or signed, has limits.

The following code will underflow:

char i;

i = 127; /* max of signed char */
i -= 100; /* i = 27 */
i -= 100; /* i = -73 */
i -= 100; /* i is utter nonsense now */

The signed value has not been "a successful model" in this instance. It was the wrong type and it failed us because we did not make assumptions about the operations that would be performed upon it, nor did we make tests to ensure what we were doing was safe.

if you're trying to model a non-negative number using an unsigned int

Which works. Imagine we want to know the difference in two numbers:

unsigned int difference( unsigned int a, unsigned int b ) {
    if ( a >= b ) {
        return( a - b );
    } else {
        return( b - a );
    }
}

This function handles any two sizes - and returns the difference. The difference will always be a positive whole number which can be represented as an unsigned int. The input sizes must be positive whole numbers as long as they are less than the maximum representable value of an unsigned int.

So now I've given you example of code using signed integers that failed. And example of code using unsigned integers that was fine and appropriate. The difference between the two was in the preconditions of the inputs and testing the values before operating on them.

The big advantage of unsigned integers that you cannot ignore include:

  • twice the typical range of a signed type
  • no ambiguity about the effect of a left or right shift (signed values behave differently depending on whether an arithmetic shift is used or not)

One of the big problems with Java's failure to include an unsigned type was that IPv4 addresses could not be represented in a 32-bit type as the most significant number was the sign bit. Thus we've had more than a decade of Java code that processes IPv4 addresses in wasteful 64-bit types. All because of fearmongering about unsigned types. What a waste.

/r/programming Thread Parent Link - i-programmer.info