I am reading "Programming Principles and Practices using C++" by Bjarne Stroustrup, and I would need a clarification about a surprising bit that I found in section 25.5.3. The author claims that if we want to iterate over an std::vector, then using a loop variable like
for (vector<int>::size_type i = 0; i < v.size(); ++i)
is less safe than using the iterators for the vector class:
for (vector<int>::iterator p = v.begin(); p != v.end(); ++p)
because, being of an unsigned type, i could overflow. He states that the loop using iterators has no such limitation. I am a bit confused, since I learned that size_type is guaranteed to be big enough to represent the biggest possible vector, so a variable of type size_type will never overflow in a loop like that.
EDIT
To be more specific, he presents an example using a loop variable of type int before the other two, then at the end he states:
"The size_type is guaranteed to be unsigned, so the first (unsigned integer) form has one more bit to play than the int version above. That can be significant, but it still gives only a single bit of range (doubling the number of iterations that can be done). The loop using iterators has no such limitation."
Doesn't vector<T>::size() return a vector<T>::size_type? I don't see any limitation.
Well, yes, the paragraph you quoted does seem to indirecly imply or hint that
size_typecan be problematic. But I don't think it was the author's intent.Note that the previous paragraph says (re: Second Edition)
In this paragraph
size_typeis presented a solution for potentially problematicintloops used in the previous sections of the book. It is mentioned as a safe alternative together with iterator or range-for version of the loop.The potential overflow (or insufficient range) problem does exist when someone tries to use
std::size_tto count or index elements of a non-array-based container, likestd::list,std::deque,std::mapetc,, instead of using container's ownsize_type. But it is a slightly different story, even if it is related.