Advanced level · Module 3: Modern C++17 and C++20 Features · Lesson 1 of 4
auto, Structured Bindings and if-initialisers
Use type deduction where it improves readability, unpack pairs and structs, and keep variables in the narrowest scope.
In this lesson you will
- Use auto appropriately
- Use structured bindings and if/switch initialisers
Key concepts
autostructured bindingsif with initialiserrange-for over maps
The lesson
auto lets the compiler deduce a variable's type from its initialiser. Use it when the type is obvious or long, such as iterators, and avoid it when the type matters to the reader, as with numeric types in calculations.
Structured bindings unpack aggregates: auto [name, count] = pair; or for (const auto& [station, reading] : readings). They make code over maps and pairs much easier to read.
if (auto it = stock.find(id); it != stock.end()) { … } declares it only for the if statement, keeping variables in the smallest possible scope.
Step by step
- Replace a long iterator type with auto.
- Loop over a map with structured bindings.
- Use an if-initialiser for a map lookup.
- Find a place where auto hides an important type and undo it.
Practice activity
Refactor a report function over a std::map using structured bindings and if-initialisers.
Expected result: The refactored function is shorter and produces identical output.
Check your understanding
-
What does auto [a, b] = p; do?
Show answer
Unpacks the two members of p into a and b.
-
When should you avoid auto?
Show answer
When the exact type matters to understanding the code, such as numeric types in calculations.
Taught live by an instructor — online or in person. Free course lessons are for self-study and do not lead to a certificate — see registration options.