Quote:Original post by Sneftel
No, that's the thing. An index of 4294967295 will access exactly the same thing as an index of -1. From the CPU's point of view, there literally is zero difference between the two situations.
My example wasn't best, the point I was trying to make is that an array index, as a value, cannot be signed. a[-1] isn't allowed, as such it makes no sense to use it. With a variable, it's possible to do it, but it's not sane. Depending on the compiler, the results might even be deterministic, but still not sane. So might as well enforce this relation.
However, unsigned types may lead to slightly more elegant code (or not, depends).
template < class T >T get( unsigned int index ) { if ( index < n_elements ) { return ... } else { // error }}
compared to:
template < class T >T get( int index ) { if ( (index >= 0) && ( index < n_elements )) { return ... } else { // error }}
since it allows you to establish hard relation. Even if a negative index is passed, it only requires one test.
The decrementing while statement is tricky as well, since subtle flaws can lead to, as mentioned, infinite loops.
Overall, unsigned types are just fine for things that are unsigned. But they come with their own set of problems and gotchas.