4 ms·
> - When storing numbers, prefer unsigned to signed because signed overflow is UB. There's an interesting caveat to this one - if you rely on sanitizers like u
by FartyMcFarter 4y ago
> - When storing numbers, prefer unsigned to signed because signed overflow is UB.
There's an interesting caveat to this one - if you rely on sanitizers like ubsan to catch overflow errors, using unsigned won't work. It will happily and silently overflow.
- Leherenn 4y agoFor what it's worth (though you likely know it), you can add "-fsanitize=unsigned-integer-overflow" to trigger a diagnostic even if unsigned integer overflow is not UB. Of course, this only works if your code does not rely on unsigned integer overflow or if you suppress each case one by one. I would tend to say this is a good practice to enable it, because the number of times where you rely on the overflow should be very low and well documented.
- FartyMcFarter 4y agoI had forgotten about that one - that's a great solution, and I agree that in most programs unsigned overflow is rarely desirable, so explicit annotation makes sense for those cases.