3 ms·
> * Finally (and this will probably be controversial), use unsigned arithmetic as much as you can! The reason for this is because unsigned arithmetic has far fe
by jcranmer 3y ago
> * Finally (and this will probably be controversial), use unsigned arithmetic as much as you can! The reason for this is because unsigned arithmetic has far fewer cases of UB, and with a little work, you can simulate two's-complement signed arithmetic in C without UB.
I would recommend against this. You're trading off one form of incorrect behavior (UB) for another form of incorrect behavior (wraparound on overflow is incorrect >99% of the time), with the added potential for mistakes in the emulation step.
Instead, do this:
* If you consider that wraparound on overflow is in fact the correct and desired behavior, use unsigned arithmetic.
* If you want to check for overflowing conditions, use your compiler's builtins for checked operations (C23 finally adds ckd_* ops, but it's too new to recommend use of yet).
- gavinhoward 3y agoOne of the reasons I recommend unsigned arithmetic is because you can make checked arithmetic from it. Doing it with signed arithmetic is a fool's errand. I have, in fact, done this.
- jcranmer 3y agoIt is best not to try to roll your own checked arithmetic. Your compiler already has an implementation, that will likely compile down to "check the overflow flag in hardware", and carries 0 risk of undefined behavior. Why not use it? ("It's not portable" is a reason that will cease to be true shortly--as mentioned, C23 added checked overflow functions.)
- gavinhoward 3y agoBecause I want to stay on C11. > Your compiler already has an implementation That's a big assumption that is not true on all compilers I want to target.
- yjftsjthsd-h 3y ago> ("It's not portable" is a reason that will cease to be true shortly--as mentioned, C23 added checked overflow functions.) So in practice, today, it's not portable and won't be for a while (even when it's released into compilers, it'll take time for those new versions to trickle into the ecosystem), which is a compelling argument against using it.