auto asks the compiler to deduce a type from an initializer or expression, replacing a type name when the type is clear from context. For example, auto x = 1 + 1.23 deduces double because integer promotion determines the result. The same idea can express a function's return type with a trailing return type, as in auto main() -> int. section 1.4.2
A small container example
A range-based loop can use auto to walk through a vector without spelling out the element type: for (auto number : data) prints each value in a vector<int>. The loop also hides iterator positions, stopping conditions, and increments, keeping attention on the container's contents. section 2.1
Listing 2.1 Filling and displaying a container
#include <iostream> #1
#include <vector> #1
void generate_triangle()
{
std::vector<int> data{ 1 }; #2
for (auto number : data) #3
{
std::cout << number << ' ';
}
std::cout << '\n';
}
int main()
{
generate_triangle();
}
Listing 2.1 shows auto in a complete vector program, including construction, iteration, and output. section 2.1
The practical payoff grows with library types. A nested vector such as std::vector<std::vector<int>> is cumbersome to write, so a function generating Pascal's triangle can return auto. Class template argument deduction similarly allows std::vector next_row{ 1 }; to infer the vector's element type. section 2.2.2 section 2.4
Listing 2.3 Generating several rows of Pascal’s triangle
auto generate_triangle(int rows) #1
{
std::vector<int> data;
std::vector<std::vector<int>> triangle;
for (int row = 0; row < rows; ++row)
{
data = get_next_row(data); #2
triangle.push_back(data); #3
}
return triangle;
}
Listing 2.3 applies auto as the return type while generating several rows of Pascal's triangle. section 2.2.2
auto also supports generic code. std::plus<> deduces its template argument types, unlike std::plus<int>, which converts 1.23 to int. A template function can combine different parameter types and use decltype(lhs + rhs) to specify the resulting return type. section 1.4.2
When using auto, keep these distinctions in mind:
- Use it in range-based loops to avoid spelling element types or iterator mechanics. section 2.1
- Use it with container construction when class template argument deduction can infer the type. section 2.4
- Use auto almost always when the deduced type remains understandable; inspect it with an IDE or C++ Insights when needed. section 2.1
- Do not confuse a deduced variable type with a freely chosen type: the initializer and expression rules determine the result. section 1.4.2


