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, and sometimes the type is already completely clear from the value you’re assigning. Writing it out anyway is just repetitive work.
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
The compiler deduces the type from the literal value, and it applies some defaults worth knowing:
- 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 explicitlyFurther ahead
As the course progresses, you’ll encounter situations where spelling out the full type becomes genuinely cumbersome. That’s where auto really earns its place. For now, know it exists and what it does.