4 ms·
Doesn't this depend? - When iterating an array, you're supposed to use "size_t", because it's the only type that's guaranteed to contain the maximum size of an
by qsort 4y ago
Doesn't this depend?
- When iterating an array, you're supposed to use "size_t", because it's the only type that's guaranteed to contain the maximum size of an array.
- When storing the difference between two pointers, you're supposed to use "ptrdiff_t" because it's the only type that's guaranteed to contain the signed difference between two related pointers.
- When storing numbers, prefer unsigned to signed because signed overflow is UB.
- 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.
- pkhuong 4y agoThis all makes sense at first sight, but remember that we can always take the difference between the address of an array's first element and one past the end, so you run into a lot of issues when an array (or any object) is larger than PTRDIFF_MAX bytes. https://trust-in-soft.com/blog/2016/05/20/objects-larger-than-ptrdiff_max-bytes/ https://trust-in-soft.com/blog/2016/05/20/objects-larger-tha...
- UncleMeat 4y agoIMO the third point is backwards. Because unsigned overflow is defined you cannot detect it with tools nearly as well but it still almost certainly represents a bug in your program. Better to find the bug with ubsan or some static analyzer than silently produce broken behavior.