4 ms·
I feel like doing arithmetic with unsigned integers is like doing all your coding 2 feet from a cliff, in return for more land about 2^63 miles away. It's fine
by CJefferson 8y ago
I feel like doing arithmetic with unsigned integers is like doing all your coding 2 feet from a cliff, in return for more land about 2^63 miles away. It's fine as long as you never make the tinyest step wrong, and its very unlikely you'll ever need that other land (and it's usually easy to design code not to need it).
This doesn't apply if you are using unsized for bit twiddling, but then you shouldn't be using minus anyway.
- ridiculous_fish 8y agoThat's a good thing: the cliff is visible (zero is familiar) and intuitive (negative numbers are unsupported). The pitfalls of signed arithmetic are much more insidious. Left shift a negative value? UB. Negate a negative value: maybe it's still negative. INT_MIN / -1? Crash! Even basic arithmetic operations, e.g. the average of two integers, is unreasonably hard with signed arithmetic.
- chopin 8y ago>Even basic arithmetic operations, e.g. the average of two integers, is unreasonably hard with signed arithmetic. What do you have in mind? I understand that the addition can overflow, but that can happen with unsigned as well.
- zbentley 8y agoI agree with you, but it doesn't sound like it would have helped things in this domain, as a negative index into a string (if they used signed ints and subtracted larger values) would have produced (according to the spec, undefined) values that were likely just as wrong.
- lostmyoldone 8y agoThere was a check for a negative difference before the array access, so signed arithmetic would have hit that check. Well, at least for any reasonable definition of signed arithmetic.
- perfmode 8y agoDoesn’t it make more sense to model counting of string length using natural numbers instead of integers? It’s sort of like a dependent type which ensures you cannot represent invalid values.
- ChrisSD 8y agoThe irony here is that the CPU will set the underflow making this trivial to detect in ASM with the `jb` instruction. The equivalent C++ would be something like: if (new_len > child.length()) As stated in the article, checking if an unsigned is less than 0 is a silly logic error but obviously one that is understandable to make. Still it's the sort of thing you'd expect automated tools would be able to catch.
- AstralStorm 8y agoThe problem is being written as <= 0. The compiler could complain "why aren't you just == 0 because it is unsigned" but that's probably enabled at -Wpedantic or such level.