liveBook · Manning

Size_t

As explained in 100 C++ Mistakes and How to Avoid Them

size_t is an unsigned integer type capable of representing the size of any object in C++.

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

How 100 C++ Mistakes and How to Avoid Them covers it

How deep it goes
Defines its size guarantee and explains unsigned wraparound in reverse loops, stopping short of broader implementation details.
Examples
Uses a vector reverse-index loop whose unsigned counter wraps after reaching zero.
What it assumes
Assumes familiarity with C++ loops, vectors, indexes, and auto type deduction.
What you can do after
Diagnose reverse-loop crashes caused by unsigned wraparound and choose int when a negative loop condition is required.
How it connects
Links type inference, auto, unsigned integer types, container sizes, and countdown loops.

Also explained in

Compare how 2 books explain size_t →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of 100 C++ Mistakes and How to Avoid Them. The section links point to the parts of the book it draws on.