size_t is an unsigned integer type guaranteed to represent the size of any object. Modern C++ often deduces it for container sizes, so use it confidently for sizes—but not blindly for countdown indexes. section 3.2
A practical distinction prevents subtle bugs:
- Use size_t when a value represents an object or container size. section 3.2
- Be cautious when auto deduces size_t for a reverse loop. An unsigned counter cannot become negative; after reaching zero, it wraps to the type's maximum value and may access outside the container. section 3.2
- For a countdown loop that must test i >= 0, use int instead of auto when that is the safer compatible correction. section 3.2
Listing 3.5 A subtle misuse of auto
int main() {
std::vector<int> values;
for (int i = 0; i < 10; ++i)
values.push_back(i*2);
for (auto i = values.size() - 1; i >= 0; --i) #1
std::cout << values[i] << '\n';
return 0;
}
This reverse-index loop demonstrates how auto deduces an unsigned size type and can lead to a segmentation fault after the counter reaches zero. section 3.2

