typestar

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

  1. int count = 42 states its type; auto ratio = 2.5 deduces double from the literal.
  2. auto name = std::string("typestar") pins the type in the initializer, not the declaration.
  3. name.size() deduces an unsigned size type; static_cast<double> converts it out loud.

Keywords and builtins used here

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.

Type this snippet

Step 1 of 3 in Values & references, step 1 of 27 in Language basics.

Next →