Pebellslearn by building
0%
RoadmapsMatrixCoursesSandboxSign in
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.

auto — Letting the Compiler Deduce

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.

The shortcut

Look at the initialiser, strip & and top-level const: that is the type. Then add back whatever you wrote around auto.

Deducing const auto& from a const intStep 1 of 4
  1. The code

    const int limit = 5; auto a = limit; auto& b = limit;

The trap is assuming auto gives you a reference. auto c = score; followed by c = 99; leaves score untouched.

Drills

Answer fast — trust the rule.

quick drill

What type does auto lives = 3; give lives?

quick drill

What type does auto boost = 1.5f; give?

quick drill

What type does auto name = "Nova"; give?

quick drill

After int score = 10; auto c = score; c = 99;, what is score?

quick drill

What happens with auto x; on its own?

Remember

  • auto fills in the type from the initialiser; it is still static.
  • Shortcut: look at the initialiser, strip & and top-level const.
  • Trap: plain auto copies; write auto& or const auto& for a reference.

Practice — level up

0/1 solved

Write your answer, then compare it with a rubric and a model answer.

ExplainCopy or the real thing?

Rocket Run has int score = 10;. One teammate writes auto c = score; c = 99;, another writes auto& r = score; r = 99;. Explain the type each gets, what happens to score in each case, and why auto x; on its own does not compile.