Skip to the workspace
Pebellslearn by building
Data Types  ›  Lesson

auto — Letting the Compiler Deduce

auto (Automatic Type Deduction) 12 minThe auto keyword asks the compiler to work out a variable's type from its initialiser, keeping static typing while dropping references and top-level const unless you ask for them.

cpp / auto — Letting the Compiler Deduce

Explore each scene at your own pace.

01 · The rule

The rule

auto — Letting the Compiler Deduce

The auto keyword asks the compiler to work out a variable's type from its initialiser, keeping static typing while dropping references and top-level const unless you ask for them.

Inspect what auto deduces, including when a reference or const qualifier is lost.

Some C++ type names are long. Looping over Rocket Run's list of enemies with an explicit iterator type means writing std::vector<Enemy>::iterator before you have said anything interesting. auto lets the compiler fill in the type for you, without giving up any of the checking.

The rule

auto fills in the type from the initialiser; it is still static.

The compiler looks at the value on the right and gives the variable exactly that type, fixed at compile time:

auto lives = 3;          // int
auto speed = 2.5;        // double
auto boost = 1.5f;       // float (the f suffix)
auto name = "Nova";      // const char*, not std::string
auto big = 5'000'000LL;  // long long

for (const auto& enemy : enemies) {  // each element, read-only, no copy
    draw(enemy);
}

Two deduction rules to know:

  • Plain auto makes a copy. It drops references and top-level const from the initialiser.
  • Write auto& for a reference, and const auto& for a read-only reference.
int score = 10;
auto  c = score;   // int, a copy
auto& r = score;   // int&, another name for score

Because the type comes from the initialiser, auto always needs one: auto x; is an error.

Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.