Re:In C++, is empty() faster than comparing the size with zero?
by joosters on Thursday October 28, 2021 @01:47PM
(#29028893)
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)
[ Parent
| on HN ]
Re:In C++, is empty() faster than comparing the size with zero?
by BeeOnRope on Thursday October 28, 2021 @03:29PM
(#29030544)
Well 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.
Re:In C++, is empty() faster than comparing the size with zero?
by DSMan195276 on Thursday October 28, 2021 @02:58PM
(#29030083)
Yes 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.
Re:In C++, is empty() faster than comparing the size with zero?
by TheCoelacanth on Thursday October 28, 2021 @06:10PM
(#29032693)
> 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.