Variables & auto in C++
Declare the type when it matters, let auto deduce it when the initializer already says it all.
#include <string>
double describe() {
int count = 42;
auto ratio = 2.5; // deduced as double
auto name = std::string("typestar");
auto letters = name.size();
return count * ratio + static_cast<double>(letters);
}
How it works
int count = 42states its type;auto ratio = 2.5deducesdoublefrom the literal.auto name = std::string("typestar")pins the type in the initializer, not the declaration.name.size()deduces an unsigned size type;static_cast<double>converts it out loud.
Keywords and builtins used here
autodescribedoubleintreturnstatic_cast
The run, in numbers
- Lines
- 9
- Characters to type
- 229
- Tokens
- 55
- Three-star pace
- 80 tpm
At the three-star pace of 80 tokens a minute, this run takes about 41 seconds.
Step 1 of 3 in Values & references, step 1 of 27 in Language basics.