0 day streak
cpp / intermediate
Snippet

Selection Statements with Scope-Limited Initializers

C++17 introduced the ability to initialize a variable directly within the 'if' or 'switch' statement. This limits the variable's scope to the conditional block, preventing namespace pollution and making the code more robust.

snippet.cpp
cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <map>
#include <iostream>
#include <string>
void find_user(int id) {
std::map<int, std::string> users = {{42, "Alice"}};
if (auto it = users.find(id); it != users.end()) {
std::cout << "Found: " << it->second << "\n";
} else {
std::cout << "ID " << id << " not present.\n";
}
// 'it' is not accessible here
}
Breakdown
1
if (auto it = users.find(id); it != users.end())
Initializes 'it' and checks the condition in a single line.
2
it != users.end()
The condition part uses the variable defined in the initializer.