On this page
  1. auto
  2. Overview
  3. Usage
  4. Gotchas

auto

Prev: builtins | Up: builtins | Next: constexpr & consteval
Rel: References & Rvalues, Structured Bindings, Templates
Ref: cppreference — auto
Tags: #public #prog #cpp #builtins #tier/core


Overview

auto deduces a variable's static type from its initializer at compile time using the same rules as template argument deduction. By default, plain auto drops top-level const and references (making a copy), so add & or const auto& when you want to borrow without copying.

Usage

auto count = 42;                 // int
const auto& name = user.name();  // borrows without copying
auto& item = items[0];           // mutable reference
auto&& fwd = get_value();        // forwarding (universal) reference

// Abbreviated function template (C++20)
auto add(auto a, auto b) {
    return a + b;
}

Gotchas

Linked from

Related notes