3 ms·
Using 2's complement is not the entire story, some CPUs can trap on overflows (MIPS for instance). X86 doesn't but it does set the carry/overflow flags in case
by simias 9y ago
Using 2's complement is not the entire story, some CPUs can trap on overflows (MIPS for instance). X86 doesn't but it does set the carry/overflow flags in case of unsigned/signed overlow to make it easy to test for it if necessary. Leaving the freedom to the implementation to catch signed overflows like it can catch divisions by zero might actually be a feature. Admittedly it's not very consistent to make unsigned overflow defined.
I like rust's approach that you can explicitly decide to use overflowing arithmetic if you want, otherwise it triggers a runtime error in debug mode. That alongside with the checked_ variants make it very easy to deal with potentially overflowing code whereas in C it's a minefield, it's not difficult to trigger an UB while trying to defend against an other UB. Ask a beginner to write a "checked_add" function in C (no Stack Overflow allowed) and see how many bugs and UB you can spot.
On the other hand advocating for implicit wrapping overflow all the time sounds risky to me. In my experience there's only a very tiny subset of operations where an overflow is desired and wouldn't lead to a bug.