2 ms·
In C++, if I use unsigned variables whenever possible, the users get an invariant for free that these indexes are never negative (though C++ has no overflow che
by nyanpasu64 5y ago
In C++, if I use unsigned variables whenever possible, the users get an invariant for free that these indexes are never negative (though C++ has no overflow checking to catch "negative" overflowing values at time of creation). Would a language with signed sizes and indexing lose out on this property, and require data structure and algorithmic/business logic to compulsively check all outside input to ensure these values are non-negative (because negative values are in the type's domain, but invalid for many algorithms)? What about compulsively checking internal state (which may/not have the intended and/or enforced invariant that internal state values are non-negative)?
- gpderetta 5y agoAs discussed elsethread, out of bounds unsigned integers are as wrong as negative indices. And checking for positive and in bound is no more expensive than checking for just within bounds. The only issue with negative indices is that it is no longer possible to have containers-of-bytes as large as the address space, but except for that tiny time window when an usable 4GB address space was actually available on 32 bits systems, it is in practice not a big restriction.