`auto` — C++ Keyword

`auto` — C++ Keyword

The auto keyword in C++: type deduction for variables, return types, and parameters.

How to use this reference page

Use reference pages to confirm names, categories, nearby facilities, and the constraints that matter before writing or reviewing code.

  • Scan the top of the page first to identify the primary types, functions, or algorithm families involved.
  • Use the nearby-page links when your question is really about a companion header, related algorithm family, or broader subsystem.
  • Validate tricky behavior with a small compileable example before relying on memory for details like invalidation, ordering, allocation, or lifetime rules.

auto

Instructs the compiler to deduce the type of a variable from its initializer, a function's return type from its return statement, or (C++20) a function parameter type.

Syntax

auto name = expression;           // deduce type
auto name = {list};               // deduces std::initializer_list
const auto& name = expression;    // deduce const reference
auto&& name = expression;         // forwarding reference

auto func() -> TrailingType;      // trailing return type
auto func() { return expr; }      // deduced return type (C++14)

void func(auto x);                // abbreviated function template (C++20)

Example

#include <print>
#include <vector>
#include <map>

int main() {
    auto i    = 42;           // int
    auto d    = 3.14;         // double
    auto s    = std::string{"hello"};

    std::vector<int> v = {1, 2, 3};
    for (const auto& x : v) {
        std::print("{} ", x);  // 1 2 3
    }
    std::println();

    std::map<int, std::string> m = {{1, "one"}, {2, "two"}};
    for (auto& [k, val] : m) {                   // structured binding
        std::println("{}: {}", k, val);
    }
}

Notes

Example in practice

int main() {
    // Pick one facility from this reference page.
    // Write the smallest program that exercises its main precondition,
    // complexity rule, or lifetime constraint before scaling up.
    return 0;
}