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
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.