liveBook · Manning

Auto

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

auto is a C++ declaration specifier that asks the compiler to deduce a variable's type from its initializer.

auto asks the compiler to deduce a variable’s type from its initializer. It removes distracting type syntax, keeps declarations aligned with their expressions, and can make modern C++ easier to maintain. section 2.0 section 3.2

Mistake: repeating types that the compiler already knows

A verbose iterator declaration hides the search being performed: `std::vector<int>::iterator it = std::find(values.begin(), values.end(), key);`. A safer modernized form is `if (auto it = std::find(values.begin(), values.end(), key); it != values.end())`, which lets the compiler supply the iterator type while keeping the logic visible. section 3.2

Use auto deliberately rather than treating deduction as universally safer:

  • Let it determine complex iterator and container-related types, reducing housekeeping and subtle spelling errors. section 3.2 section 6.8
  • Check the deduced type in countdown loops: `values.size()` produces an unsigned size-related type, so decrementing past zero can wrap and access outside the container. section 3.2
  • When the loop genuinely needs a signed counter, use `int` instead of forcing auto into an unsuitable deduction. section 3.2
Listing 3.4 Using auto to let the compiler deduce correct types
int main() {
    std::vector<int> values;
    for (auto i = 0; i < 10; ++i)                           #1
        values.push_back(i*2);
    int key = 4;
    if (auto it = std::find(values.begin(), 
            values.end(), key); it != values.end())         #2
        std::cout << key << " was found\n";
    else
        std::cout << key << " was not found\n";
    return 0;
}

Compare an index loop and a search iterator after replacing explicit iterator syntax with auto. section 3.2

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

How deep it goes
Explains initializer-based deduction and a signedness failure, but does not develop deduction rules beyond these practical cases.
Examples
Uses index loops, vector searches, iterator declarations, reverse iteration, and references returned from student names.
What it assumes
Assumes basic C++ variables, loops, vectors, and iterators while teaching compiler-directed type deduction through examples.
What you can do after
Evaluate/understand when deduction improves declarations and when an explicitly signed counter prevents unsigned wraparound.
How it connects
Connects type inference with iterators, STL containers, range-based for loops, and size_t.

Also explained in

Compare how 3 books explain auto →

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.