Hacker News new | past | comments | ask | show | jobs | submit login

>unsigned is trivial (just test `a+b < b`)

Nitpicking, the test itself should avoid overflowing. Instead, test "a <= UINT_MAX - b" to prove no overflow occurs.

For signed integers, we need to prove the following without overflowing in the test: "a+b <= INT_MAX && a+b >= INT_MIN". The algorithm follows: test "b >= 0", which implies "INT_MAX-b <= INT_MAX && a+b >= INT_MIN", so then test "a <= INT_MAX-b". Otherwise, "b < 0", which implies "INT_MIN-b >= INT_MIN && a+b <= INT_MAX", so then test "a >= INT_MIN-b".




> Nitpicking, the test itself should avoid overflowing.

Why? Overflowing is well defined for unsigned.


Personal preference, hence nitpicking. It forms a special case of the signed integer algorithm, which feels nice.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: