- C++17 STL Cookbook
- Jacek Galowicz
- 190字
- 2025-04-04 19:00:06
How it works...
The if and switch statements with initializers are basically just syntax sugar. The following two samples are equivalent:
Before C++17:
{
auto var (init_value);
if (condition) {
// branch A. var is accessible
} else {
// branch B. var is accessible
}
// var is still accessible
}
Since C++17:
if (auto var (init_value); condition) {
// branch A. var is accessible
} else {
// branch B. var is accessible
}
// var is not accessible any longer
The same applies to switch statements:
Before C++17:
{
auto var (init_value);
switch (var) {
case 1: ...
case 2: ...
...
}
// var is still accessible
}
Since C++17:
switch (auto var (init_value); var) {
case 1: ...
case 2: ...
...
}
// var is not accessible any longer
This feature is very useful to keep the scope of a variable as short as necessary. Before C++17, this was only possible using extra braces around the code, as the pre-C++17 examples show. The short lifetimes reduce the number of variables in the scope, which keeps our code tidy and makes it easier to refactor.