←back to thread

93 points endorphine | 1 comments | | HN request time: 0.218s | 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 #
1. steveklabnik ◴[] No.43539954[source]
You're right that this test would be UB for signed integers.

See here for that in action, as well as one way to test it that does work: https://godbolt.org/z/sca6hxer4

If you're on C23, uercker's advice to use these standardized functions is the best, of course.