Data Types
Auto Type
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
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;
}
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
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
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
countstarts at4.doublediscount * 2.doubledbecomes8.labelstaysitems.- The program prints
count=4,doubled=8, andlabel=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.