liveBook · Manning

Off-by-one error

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

An off-by-one error is a boundary error in which an iteration or index range includes one element too many or too few.

An off-by-one error includes one element too many or too few. In an indexed loop over a container, changing the continuation test from `i < values.size()` to `i <= values.size()` is an intuitive-looking mistake that crosses the boundary. section 2.6

A mistaken loop bound

When summing a vector, `i <= values.size()` is incorrect: the last valid index is reached before the loop condition becomes false. A range-based for loop avoids writing that boundary test. section 2.6

Listing 2.12 Using range-based for values when iterating over a container
template <typename T>
T sum(const std::vector<T>& values) {
    T sum {};                                             #1
    for (const T& value : values)                         #2
        sum += value;
    return sum;
}
 
int main() {
    std::vector<int> values;
    for (int i = 0; i < 10; ++i)                          #3
        values.push_back(10*i + i);
    std::cout << sum(values) << '\n';
    return 0;
}

This range-based version sums each container element without manually writing index bounds. It uses a const reference for the loop variable. section 2.6

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

How deep it goes
Explains the mistaken bound and demonstrates a range-based correction, without pursuing broader boundary-error cases.
Examples
Uses a vector-summing loop and contrasts its index-based form with a range-based version.
What you can do after
Apply range-based for loops to iterate through containers without manually specifying index bounds.
How it connects
Connects indexed loops, containers, and range-based for loops.

Also explained in

Compare how 4 books explain off-by-one error →

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.