But that's just rephrasing the question. Why would you define int math that way? Is it due to concern about unexpected traps escalating a system failure, like the one that destroyed the first Ariane 5?
Conversation
This Tweet was deleted by the Tweet author. Learn more
This Tweet was deleted by the Tweet author. Learn more
Well, we did talk about two reasons to change it earlier in the thread; did you read that part?
1
From my perspective, regardless of how people want to handle unintended overflow, explicit intended overflow for new languages and new code in older languages can reach consensus. For signed in C it's barely even a discussion since you can't rely on it while being portable.
1
1
If you want portable signed overflow, you *already* have to define functions for it, which can use __builtin_mul_overflow when available (add/sub is trivial anyway) and otherwise implement it by hand. GCC -fwrapv is also notably not complete and not a good idea to rely on too.
2
This is probably not a viable solution to using wrapping types just due to the amount of noise it adds to your code
1
It's noisy, but C doesn't support custom arithmetic types like Rust. Swift has wrapping operators. Wrapping is only commonly used for unsigned integers though. It's rarely ever wanted for signed integers, and is mostly a quirk of hardware rather than something actually used.
1
2
doc.rust-lang.org/std/num/struct is the Rust approach for something like a cryptographic cipher using modular arithmetic. It's not very normal to want it though and I don't think Rust's signed wrapping support is particularly useful, but rather it's mostly just there for completeness.
1
I can't actually come up with a good example of anything that'd want wrapping signed arithmetic. Lots of examples of unsigned, although in the vast majority of cases you don't but rather want a larger fixed-size type or if that isn't large enough a big integer type instead.
The checked_add, checked_sub, checked_mul methods are quite commonly used. I heavily use comparable functions in my C code implemented via the same underlying LLVM (and GCC) intrinsics when possible. It's needed a high % of the time to write correct code, way more than people do.
1
All the cases I can think of would work just as well with wrapping unsigned arithmetic, aside from the cases I mentioned previously where the worst possible thing you can do is to crash the program
1
1
I'm sure you would still want it to trap in your usual debug builds though, even more so than usual, and you just can't have that kind of dynamic bug finding if you don't separate the intended overflows. In 2019, I kinda expect any decent C project to be using ASan and UBSan.
2
Show replies
