5 ms·
Isn't the unsigned version the correct one? Presumably the int version will hit the same problem as in the original article, in that the C spec says that ints a
by joosters 5y ago
Isn't the unsigned version the correct one? Presumably the int version will hit the same problem as in the original article, in that the C spec says that ints are not treated as overflowing? (i.e. the compiler cannot assume that adding one will eventually turn negative and then later on reach 0)
- DSMan195276 5y agoYes that's right - unsigned is defined to wrap, but ints have undefined behavior if you add to the max value (or do other silly things with them). Thus the int version given could be optimized to do whatever when a positive integer is passed, since it only doesn't have UB when negatives or zero are passed.
- BeeOnRope 5y agoWell the int version returns the correct answer for "empty()" unlike unsigned. The size of a list of 2^32-1 elements should not be reported as zero, nor as "empty". In this case, the compiler has to enforce wrap semantics for unsigned, which is an applicaton-level level bug if it occurs, and doesn't need to enforce it for int, which happens to lead to the right answer for empty (i.e., it checks if it has at least one element, which continues to return the correct "not empty" answer for 2^32-1 or 2^31-1 elements). Both get the wrong answer for size() (over different domains), if you allow lists that large: they can't even represent very large lists.
- TheCoelacanth 5y ago> the compiler cannot assume that adding one will eventually turn negative and then later on reach 0 Signed overflow is undefined behavior, so it is allowed to assume that. It's also allowed to assume anything else that it wants to. Once you cause a signed overflow, all guarantees are out the window and the compiler can do anything it wants to.