cpp / intermediate
Snippet
Scoped Initialization in Conditional Blocks
Introduced in C++17, the 'if' statement with an initializer allows you to declare and initialize a variable whose scope is limited strictly to the 'if' and 'else' branches. This prevents variable leakage into the surrounding scope, improving code safety and readability.
snippet.cpp
cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream>#include <map>int main() {std::map<std::string, int> scores = {{"Alice", 10}, {"Bob", 20}};// C++17 'if' with initializer: 'it' is only visible inside this blockif (auto it = scores.find("Alice"); it != scores.end()) {std::cout << "Found: " << it->second << std::endl;} else {std::cout << "Not found" << std::endl;}return 0;}
Breakdown
1
if (auto it = scores.find("Alice"); it != scores.end())
Declares 'it' and checks the condition in a single line. 'it' only exists within this 'if/else'.