←back to thread

93 points endorphine | 1 comments | | HN request time: 0.217s | source
Show context
uecker ◴[] No.43537642[source]
You can implement C in completely different ways. For example, I like that signed overflow is UB because it is trivial to catch it, while unsigned wraparound - while defined - leads to extremely difficult to find bugs.
replies(4): >>43537908 #>>43538002 #>>43538056 #>>43538186 #
Strilanc ◴[] No.43538056[source]
Could you provide the code you use to trivially catch signed overflows? My impression is the opposite: unsigned is trivial (just test `a+b < b`) while signed is annoying (especially because evaluating a potentially-overflowing expression would cause the UB I'm trying to avoid).
replies(6): >>43538172 #>>43538229 #>>43538928 #>>43539940 #>>43539954 #>>43541133 #
amavect ◴[] No.43541133[source]
>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".

replies(1): >>43542957 #
lelanthran ◴[] No.43542957[source]
> Nitpicking, the test itself should avoid overflowing.

Why? Overflowing is well defined for unsigned.

replies(1): >>43552153 #
1. amavect ◴[] No.43552153[source]
Personal preference, hence nitpicking. It forms a special case of the signed integer algorithm, which feels nice.