01 / 21
a ?

Type Inference
with \(\text{auto}\)

Learn how C++ can automatically deduce types for you, making code cleaner, safer, and more maintainable.

C++

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.

Explicit Typing
You tell the compiler what type to use: \(\text{int x = 5;}\)
Type Inference
The compiler deduces the type: \(\text{auto x = 5;}\)

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.

Readability
Shorter declarations make code easier to scan and understand.
Safety
The compiler never guesses wrong: the type is always exact.
Maintainability
Change a function's return type and \(\text{auto}\) adapts automatically.

Before and After \(\text{auto}\)

Before (explicit)
int x = 42;
double pi = 3.14;
std::string s = "hi";
std::vector<int>::
iterator
it
= v.begin();
After (auto)
auto x = 42;
auto pi = 3.14;
auto s = "hi"s;
auto it
= v.begin();
Same types, less noise

The Core Rule of \(\text{auto}\)

auto
x
=
expression
; type flows from expression to variable keyword name initializer

How the Compiler Deduces Types

auto n = 10;
Deduced: int (integer literal)
auto d = 3.14;
Deduced: double (decimal)
auto b = true;
Deduced: bool (boolean literal)
auto c = 'A';
Deduced: char (char literal)
auto s = "hi";
Deduced: const char* !

\(\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}\)

1
Write \(\text{auto}\) where you would normally write the type name.
2
Provide an initializer. The right side of \(=\) must exist: a literal, a function call, or another variable.
3
Check the deduced type mentally. Ask: "What type does the expression return?" That's the type of your variable.
4
Add qualifiers if needed. Use \(\text{const auto}\) or \(\text{auto\&}\) to preserve const-ness or references.

Example 1: Basic Declarations

// Integer from literal auto count = 100; // int // Double from arithmetic auto half = count / 2.0; // double // Bool from comparison auto isPositive = count > 0; // bool

Example 2: Function Returns

std::string greet(std::string name) { return "Hello, " + name + "!"; } // auto deduces std::string auto message = greet("Alice");

This is especially powerful when working with library functions whose return types are long template names.

Example 3: Iterators and Loops

std::vector<int> nums = {1, 2, 3, 4, 5}; // Without auto (verbose!): for (std::vector<int>::iterator it = nums.begin(); it != nums.end(); ++it) { ... } // With auto (clean!): for (auto it = nums.begin(); it != nums.end(); ++it) { ... } // Range-based for (even cleaner!): for (auto val : nums) { ... }

\(\text{const auto}\) and \(\text{auto\&}\)

int x = 10; auto a = x; // int (copy) auto& b = x; // int& (reference) const auto c = x; // const int (read-only copy) const auto& d = x; // const int& (read-only ref)
\(\text{auto}\)
Creates a copy. Changes to the copy don't affect the original.
\(\text{auto\&}\)
Creates a reference. Changing it changes the original.
\(\text{const auto\&}\)
Read-only reference. Most efficient for just reading data.

The Stripping Behavior

Plain \(\text{auto}\) drops top-level const and references. This is the most common source of surprises. Consider this:

const int x = 42; auto y = x; // int, NOT const int! y = 99; // OK: y is a mutable copy int a = 10; int& ref = a; auto b = ref; // int, NOT int&! b = 20; // a is still 10

Where \(\text{auto}\) Shines Most

1
Complex template types: \(\text{std::unordered\_map>::iterator}\) becomes just \(\text{auto}\).
2
Lambda expressions: Lambdas have unnamed types that cannot be spelled out. You must use \(\text{auto}\).
3
Range-based for loops: \(\text{for (auto\& item : collection)}\) is cleaner and adapts if the container type changes.
4
Structured bindings (C++17): \(\text{auto [key, value] = pair;}\) unpacks pair/tuple members.

Common Mistakes with \(\text{auto}\)

No Initializer
Writing \(\text{auto x;}\) without \(= \text{value}\) causes a compile error. The compiler needs something to deduce from.
String Literal Trap
\(\text{auto s = "hello";}\) deduces \(\text{const char*}\), not \(\text{std::string}\). Use the \(\text{s}\) suffix or explicit type.
Forgetting &
Using \(\text{auto}\) instead of \(\text{auto\&}\) in a loop creates copies of each element, which is slow for large objects.

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?