Skip to content
Tutorials Center
My learning

Topics

Lesson 14 of 171 ยท Variables and Types

Type Deduction with auto

Learn exactly what C++ auto deduces, why it drops const and references, when to use auto&, const auto& and auto&&, how decltype differs, and when auto helps readability.

Writing std::vector<std::pair<std::string, int>>::const_iterator once is tedious. Writing it ten times is how bugs and typos get in. Since C++11, you can write auto instead of a type, and the compiler works out the type from the initializer. auto is not dynamic typing: the variable still gets one fixed type at compile time, exactly as if you had spelled it out.

The keyword is easy to use and easy to misuse. auto follows precise rules that drop const and references unless you ask for them, and a few initializers deduce types nobody expects. In this lesson you'll learn those rules, the auto&, const auto& and auto&& variations, the related decltype, and the judgment call of when auto makes code clearer.

The basics

auto takes its type from the initializer, so a variable declared with auto must be initialized:

C++
auto count = 10;          // int
auto ratio = 0.75;        // double
auto ratio_f = 0.75f;     // float
auto initial = 'R';       // char
auto big = 10'000'000'000LL;  // long long
auto done = false;        // bool

auto mystery;             // error: declaration of 'auto mystery' has no initializer

The deduced type is exactly the initializer's type, so literal rules from Integer Types and Floating-Point Numbers matter: auto x = 5; is an int, auto x = 5u; is unsigned int, and auto x = 5.0; is a double.

auto shines when the type is long, obvious from the right-hand side, or both:

C++ Where auto earns its keep

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

The iterator type, the unique_ptr type, and the pair type inside the loop are all long, and none of them would make the code clearer if spelled out. The [name, list] syntax is a structured binding, which only works with auto; you'll use it again in Returning Values and std::map.

Seeing what auto deduced

To learn the rules, it helps to see the deduced types. C++ has no standard "print this type's name" function, but GCC and Clang put the full signature of the current function, including template arguments, into the predefined __PRETTY_FUNCTION__ string. The small type_name helper below extracts the type from it. It is a compiler-specific teaching tool, not something to ship, and it uses templates you'll learn later in Function Templates. Just use it:

C++ auto drops const and references

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

That output is the most important rule of this lesson:

Plain auto always makes a new, independent object. It deduces the type by value: references are removed, and then top-level const is removed, because a copy doesn't need to be const just because the original was. If you want a reference, write auto& or const auto&. If you want a constant copy, write const auto.

"Top-level" const means const that applies to the variable itself. In const int* p the const belongs to the thing pointed to, so it is kept by auto: copying the pointer doesn't let you modify the int it points to. You'll meet this distinction again in const with Pointers and References.

The four forms you'll actually use

Form Gives you Use it when
auto x = expr; a copy you want your own value (numbers, small objects, results of functions)
const auto x = expr; a copy you can't change the value is fixed after initialization
auto& x = expr; a reference you can modify through you want to change the original (e.g. elements in a loop)
const auto& x = expr; a read-only reference you want to look at something big without copying it

The difference is most visible, and most expensive to get wrong, in range-based for loops:

C++ Copies vs references in loops

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

The first loop copies every string, modifies the copies, and throws them away: a silent no-op that also costs an allocation per element for long strings. The rule of thumb: const auto& for reading anything bigger than a few machine words, auto& for modifying, plain auto for small values like numbers and pointers.

Surprises to know about

Most deductions are exactly what you expect. These are the exceptions:

C++ Deductions that surprise people

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

What each line teaches:

  • String literals deduce const char*, a pointer to C-style characters, not std::string. That means no .size(), no + concatenation with another literal. Write std::string s = "hello"; or use the s suffix from std::string_literals. The helper prints std::string by its full internal name, std::__cxx11::basic_string<char>; __cxx11 is just a namespace inside GCC's standard library. (Inside std::println, {{ and }} print literal braces.)
  • auto x{5} is an int, but auto x = {5} is an std::initializer_list<int>. Prefer auto x = 5; and avoid the second form unless you really want a list.
  • .size() returns std::size_t, an unsigned type (shown as long unsigned int on our server). auto n = v.size(); n - 1 wraps on an empty vector, exactly the trap described in Integer Types.
  • std::vector<bool> returns a proxy object (here std::_Bit_reference, a libstdc++ internal name) because it packs bits. If the vector is destroyed or changed, the proxy can dangle. Write bool first = flags[0]; when you mean a bool.

auto&& in one paragraph

auto&& looks like an rvalue reference, but in deduction it is a forwarding reference: it binds to anything, becoming an lvalue reference for named objects (auto&& r = limit; gives const int&) and an rvalue reference for temporaries (auto&& r = 3; gives int&&). You'll mostly see it in generic code, for example for (auto&& x : range) when the elements might be proxies, and in perfect forwarding. In everyday code, auto& and const auto& say more clearly what you mean.

decltype: the type of an expression

auto deduces a type for a new variable. decltype(expr) asks for the type of an existing expression, without evaluating it, and without dropping anything:

C++
const int limit = 10;
const int& ref = limit;

decltype(limit) a = 5;   // const int   (const is kept)
decltype(ref) b = a;     // const int&  (reference is kept)
decltype(limit + 1) c;   // int         (an arithmetic result is a plain int)

There is one subtle rule. For a plain name, decltype gives the declared type of that variable. For any other expression that refers to an object, including a name wrapped in parentheses, it gives a reference type:

C++
int x = 0;
decltype(x)   d1 = x;    // int
decltype((x)) d2 = x;    // int&  (the parentheses make it an expression)

decltype(auto) (C++14) combines both: deduce from the initializer like auto, but with decltype's rules, so references and const are kept. It is mainly used for function return types in generic code that must return exactly what another function returns. Day to day, you'll use decltype most often to say "the same type as that variable": decltype(total) running = 0;.

auto for function return types

Functions can deduce their return type too:

C++ Deduced return types

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

Every return in a deduced function must produce the same type, and like plain auto variables, it returns by value. Deduced return types are great for short functions and templates; for public functions in headers, an explicit return type documents the interface better. The trailing -> type syntax is required in some template situations and preferred by some style guides; it means the same thing as writing the type at the front.

C++20 even allows auto in parameter lists (void print_twice(auto value)), which quietly makes the function a template. That's covered in Function Templates.

When should you use auto?

C++ programmers debate this endlessly. Here are guidelines that most experienced teams agree on:

Use auto when:

  • the type is already visible on the right: auto p = std::make_unique<Widget>();, auto n = static_cast<int>(x);
  • the type is long and adds no information: iterators, nested container types, lambdas (whose types can't be written at all)
  • the exact type doesn't matter to the reader, such as structured bindings and loop variables over containers
  • you want to avoid accidental conversions: auto size = v.size(); gets the right type, while int size = v.size(); silently narrows

Spell out the type when:

  • the type is the information: std::int64_t total_bytes = 0; or double ratio = 1; (with auto, 1 would make an int)
  • the initializer could deduce something surprising (string literals, {...}, proxy types)
  • a reader would otherwise have to look up a function's declaration to know what they have

Whichever you choose, name variables well. auto user_count = users.size(); is clearer than std::size_t n = users.size();, because the name carries the meaning and the type is obvious from context. Modern IDEs also show the deduced type when you hover over the variable.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. const std::string name = "Ada"; auto copy = name; What is the type of copy?

    Plain auto makes an independent copy and drops top-level const, so copy is a modifiable std::string.
  2. 2. What does this print? std::vector<int> v{1, 2, 3}; for (auto x : v) { x *= 10; } std::println("{}", v);

    Each x is a copy of an element, so the multiplication changes only the copies. Use auto& to modify the elements.
  3. 3. What type does auto greeting = "hi"; deduce?

    A string literal is an array of const char, and auto deduction decays it to a pointer, const char*. Use std::string or the "s" suffix if you want a std::string.
  4. 4. Which loop variable is best for reading every element of a std::vector<std::string> without modifying it?

    const auto& avoids copying each string and makes accidental modification a compile error.
  5. 5. int x = 0; What is decltype((x))?

    For an unparenthesized name, decltype gives its declared type (int). With extra parentheses it is an expression referring to an object, so decltype gives int&.

Summary

  • auto deduces a variable's type from its initializer at compile time; the variable must be initialized and its type never changes.
  • Plain auto copies: it drops references and top-level const. Use auto& to modify the original, const auto& to read without copying, and const auto for a fixed copy.
  • In range-for loops, auto copies each element; prefer const auto& for strings and objects and auto& to modify.
  • Watch the surprises: string literals give const char*, auto x = {5} gives an initializer_list, .size() gives unsigned std::size_t, and vector<bool> gives a proxy.
  • decltype(expr) reports an expression's type without evaluating it and keeps const and references; decltype((x)) is a reference.
  • Functions can deduce return types with auto. Use auto where it removes noise, and spell out types where the type itself is the information.

Next: Constants: const, constexpr and consteval, where you'll make values that can't change, and values the compiler computes before your program runs.