cpp / intermediate
Snippet
Switch Statement with Local Initialization
C++17 introduced the ability to initialize a variable directly within the switch statement's scope. This keeps the variable 'code' local to the switch block, preventing namespace pollution and improving memory safety by limiting the variable's lifetime to where it is actually needed.
snippet.cpp
cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>int get_code() { return 404; }int main() {// C++17 init-statement in switchswitch (int code = get_code(); code) {case 200:std::cout << "Success" << std::endl;break;case 404:std::cout << "Not Found: " << code << std::endl;break;default:std::cout << "Unknown" << std::endl;break;}return 0;}
Breakdown
1
switch (int code = get_code(); code)
Initializes 'code' and immediately uses it as the condition for the switch.
2
case 404:
Checks if the initialized 'code' matches the constant value 404.