0 day streak
cpp / intermediate
Snippet

Conditional Variable Scope Limiting

C++17 introduced selection statements with initializers. This allows you to initialize a variable within the if-statement scope, keeping the namespace clean and preventing accidental reuse of loop/iterator variables.

snippet.cpp
cpp
1
2
3
4
5
6
7
8
9
10
11
12
#include <iostream>
#include <vector>
int main() {
std::vector<int> nums = {1, 2, 3};
if (auto it = nums.begin(); it != nums.end()) {
std::cout << "First element: " << *it << std::endl;
}
// 'it' is not accessible here
return 0;
}
Breakdown
1
if (auto it = nums.begin(); it != nums.end())
Initializes 'it' and checks the condition in a single line; 'it' is valid only inside the if/else block.