The auto keyword lets C++ infer a variable type from its initializer.

auto `auto` asks the compiler to choose the type from the value on the right side of `=`.

Auto Type

count
auto_type.cpp
Replay: real traced execution (multi-file project)
#include <iostream>
#include <string>

int main() {
    int count = 4;
    auto doubled = count * 2;
    auto label = std::string("items");

    std::cout << "count=" << count << std::endl;
    std::cout << "doubled=" << doubled << std::endl;
    std::cout << "label=" << label << std::endl;
    return 0;
}
#include <iostream>
#include <string>

int main() {
    int count = 2;
    auto doubled = count * 2;
    auto label = std::string("items");

    std::cout << "count=" << count << std::endl;
    std::cout << "doubled=" << doubled << std::endl;
    std::cout << "label=" << label << std::endl;
    return 0;
}
#include <iostream>
#include <string>

int main() {
    int count = 7;
    auto doubled = count * 2;
    auto label = std::string("items");

    std::cout << "count=" << count << std::endl;
    std::cout << "doubled=" << doubled << std::endl;
    std::cout << "label=" << label << std::endl;
    return 0;
}
  1. count ← 4, doubled ← 8, label ← items

    4int main() {5    int count→ 4 = 4; //@count=2, 76    auto doubled→ 8 = count4 * 2;7    auto label→ items = std::string("items");89    std::cout << "count=" << count4 << std::endl;10    std::cout << "doubled=" << doubled8 << std::endl;11    std::cout << "label=" << labelitems << std::endl;12    return 0;13}
    outputcount=4
    doubled=8
    label=items
  1. count ← 2, doubled ← 4, label ← items

    4int main() {5    int count→ 2 = 2;6    auto doubled→ 4 = count2 * 2;7    auto label→ items = std::string("items");89    std::cout << "count=" << count2 << std::endl;10    std::cout << "doubled=" << doubled4 << std::endl;11    std::cout << "label=" << labelitems << std::endl;12    return 0;13}
    outputcount=2
    doubled=4
    label=items
  1. count ← 7, doubled ← 14, label ← items

    4int main() {5    int count→ 7 = 7;6    auto doubled→ 14 = count7 * 2;7    auto label→ items = std::string("items");89    std::cout << "count=" << count7 << std::endl;10    std::cout << "doubled=" << doubled14 << std::endl;11    std::cout << "label=" << labelitems << std::endl;12    return 0;13}
    outputcount=7
    doubled=14
    label=items

Follow the Inferred Values

  1. count starts at 4.
  2. doubled is count * 2.
  3. doubled becomes 8.
  4. label stays items.
  5. The program prints count=4, doubled=8, and label=items. | count | doubled | label | | --- | --- | --- | | 2 | 4 | items | | 4 | 8 | items | | 7 | 14 | items |

Exercise: auto_type.cpp

Reproduce doubled=8, then use count 2 and 7 to predict each doubled value.