Home

#8 auto Keyword

What “auto” really means in C++

“auto” tells the compiler: “Deduce the variable’s type from its initializer.”

Type deduction happens at compile time.

There is no runtime cost. The compiler substitutes the deduced type exactly as if you had written it yourself. Here are some examples:

auto x = 42;
auto y = 3.14;
auto z = "Hi";

In the first line the auto is replaced by int.
In the second line auto is replaced by double. 
In the third line auto is replaced by const char*
  

One common beginner mistake is to omit the initializer.

auto value; // this will cause a compile time error.

“auto” preserves constness and references

int n = 10;
int& ref = n;

auto a = ref;   // a is int (copy)
auto& b = ref;  // b is int& (reference)
const auto c = ref; // c is const int

“auto” behaves like template type deduction

“auto” can deduce complex types

std::vector<int> numbers = {1, 2, 3, 4};
auto it = numbers.begin();   // deduces std::vector<int>::iterator

Without auto you would need to type

std::vector<int> numbers = {1, 2, 3, 4};
std::vector<int>::iterator it = numbers.begin();