Type Inference
with \(\text{auto}\)
Learn how C++ can automatically deduce types for you, making code cleaner, safer, and more maintainable.
What Is Type Inference?
In most C++ code you've written so far, you explicitly state the type of every variable. Type inference lets the compiler figure out the type for you based on the value you assign.
Why \(\text{auto}\) Matters
C++ is a statically typed language: every variable has a fixed type at compile time. But types can get long and complex. The \(\text{auto}\) keyword (introduced in C++11) reduces verbosity without sacrificing type safety.
Before and After \(\text{auto}\)
The Core Rule of \(\text{auto}\)
How the Compiler Deduces Types
\(\text{auto}\) vs Explicit Types
| \(\text{auto}\) | Explicit Type | |
|---|---|---|
| Verbosity | Low | Can be high |
| Readability | Cleaner for complex types | Clearer for simple types |
| Type safety | Same (compile-time) | Same (compile-time) |
| Requires initializer? | Yes, always | No |
| Can cause surprises? | Yes (e.g., \(\text{const char*}\)) | No |
How to Apply \(\text{auto}\)
Example 1: Basic Declarations
Example 2: Function Returns
This is especially powerful when working with library functions whose return types are long template names.
Example 3: Iterators and Loops
\(\text{const auto}\) and \(\text{auto\&}\)
The Stripping Behavior
Plain \(\text{auto}\) drops top-level const and references. This is the most common source of surprises. Consider this:
Where \(\text{auto}\) Shines Most
Common Mistakes with \(\text{auto}\)
Summary: \(\text{auto}\) Cheat Sheet
| Declaration | Deduced Type | Key Behavior |
|---|---|---|
| \(\text{auto x = 42;}\) | \(\text{int}\) | Mutable copy |
| \(\text{auto x = 3.14;}\) | \(\text{double}\) | Mutable copy |
| \(\text{auto x = "hi";}\) | \(\text{const char*}\) | Not \(\text{std::string}\)! |
| \(\text{auto\& x = y;}\) | Reference to y's type | Aliases y |
| \(\text{const auto x = y;}\) | const copy of y's type | Read-only copy |
| \(\text{const auto\& x = y;}\) | const ref to y's type | Read-only alias |
Question 1 of 5
What is the deduced type of \(x\) in the following code?
\(\text{auto x = 7.5f;}\)
Question 2 of 5
Which of the following will cause a compile error?
Question 3 of 5
Given:
\(\text{const int x = 5; auto y = x;}\)
What is the type of y?
Question 4 of 5
What is the deduced type of \(s\)?
\(\text{auto s = "hello";}\)
Question 5 of 5
In a range-based for loop, which form avoids copying elements while also preventing modification?