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
automakes a copy. It drops references and top-levelconstfrom the initialiser. - Write
auto&for a reference, andconst auto&for a read-only reference.
int score = 10;
auto c = score; // int, a copy
auto& r = score; // int&, another name for scoreBecause 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.
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.
What type does auto lives = 3; give lives?
What type does auto boost = 1.5f; give?
What type does auto name = "Nova"; give?
After int score = 10; auto c = score; c = 99;, what is score?
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-levelconst. - Trap: plain
autocopies; writeauto&orconst auto&for a reference.
