0 day streak
cpp / intermediate
Snippet

Initializers within Selection Statements

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

snippet.cpp
cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>
#include <vector>
#include <algorithm>
int main() {
std::vector<int> data = {1, 5, 8, 12, 15};
// C++17 'if' with initializer
if (auto it = std::find(data.begin(), data.end(), 8); it != data.end()) {
std::cout << "Found value at index: " << std::distance(data.begin(), it) << "\n";
} else {
std::cout << "Value not found\n";
}
// 'it' is no longer in scope here
return 0;
}
Breakdown
1
if (auto it = std::find(data.begin(), data.end(), 8); it != data.end())
Initializes 'it' and checks the condition in one line; 'it' is only valid within the if/else blocks.