It is well-defined for using unsigned integers (and unsigned size_t ) in this way with wraparound: this behavior is guaranteed by the standard, and not with familiar integers where it is not guaranteed by the standard.
However, it is useless.
Typically, to avoid problems due to implicit unsigned ad campaigns, use unsigned integers for bit level data, use unsigned integers for numbers. Where you need a signed integer corresponding to size_t there ptrdiff_t for you. Define a function n_items with a signed result, for example
using Size = ptrdiff_t; template< class Container > auto n_items( Container const& c ) -> Size { return end( c ) - begin( c ); }
and you are set to work, no more stupid supporters of the compiler.
Instead of too smart given code
vector<int> v { 1,2,3,4,5 }; bool rev = true; size_t start, end, di; if (rev) { start = v.size()-1; end = -1; di = -1; } else { start = 0; end = v.size(); di = 1; } for (auto i=start; i!=end; i+=di) { cout << v[i] << endl;
execute for example
const vector<int> v { 1,2,3,4,5 }; const bool reverse = true;
source share