Daily bit(e) of C++ | Init statements
Daily bit(e) of C++ #125, The C++17 (if, switch) and C++20 (range-for) init statements.

Init statements enable fully encapsulated if, switch (C++17) and range-for loop (C++20) statements by adding an additional init section that can be used to create variables with a lifetime matching the statement block.
#include <string>
#include <optional>
std::optional<int> some_call() {
return 10;
}
int other_call() { return 10; }
// C++17
if (auto result = some_call(); result.has_value()) {
int v = *result;
}
// C++17
switch (auto val = other_call(); val) {
case 1: // further process val
break;
case 2: // further process val
break;
default:
;
}
// C++20 / Enables iteration over temporary ranges.
for(std::string v = std::to_string(42); auto c : v) {
// v is a valid range that can be safely iterated over
}