Type Deduction with auto
Every time you write a variable declaration in C++, you give it a type. That works fine when the type is short and obvious. But C++ types can get long and complicated. Consider this declaration (don’t worry about understanding what it does at this point):
std::vector<std::pair<std::string, int>>::iterator it = employees.begin();It turns out there’s a way to avoid specifying the type of a variable in C++, as long as the type is already clear from the value you’re assigning it. In such a case, the compiler figures out the type for you.
What auto does
When you write auto instead of a type name, you’re telling the compiler: “you figure out the type.” This is called type deduction. The compiler looks at the right-hand side of the assignment and determines the type for you.
auto score = 42; // intauto price = 19.99; // doubleauto initial = 'K'; // charauto passed = true; // boolThe types here are just as precise as if you had written them yourself. score is still an int. price is still a double.
auto is purely a convenience at the point you write the code. By the time the program runs, every variable has a concrete, fixed type. This means C++ is still statically typed. The type is determined once, at compile time, and it stays that way.
Type deduction defaults
When the compiler deduces the type from the literal value, it applies some defaults:
- Integer literals like
50deduce asint, notshortorlong. - Floating-point literals like
3.14deduce asdouble, notfloat.
If you need something other than the default, use a suffix or declare explicitly:
auto a = 3.14; // doubleauto b = 3.14f; // floatauto c = 3; // intauto d = 3L; // longshort e = 3; // there is no suffix for short, so declare explicitly