cpp17 · medium
C++17: if / switch With Initializer
C++17 adds an optional init-statement to if and switch: if (init; condition) and switch (init; condition) declare a variable whose scope is exactly that statement — visible in both the then and else branches (and across all switch cases) and destroyed at the end. This generalizes the long-standing for-loop init rule to if and switch, keeping short-lived handles such as map iterators, lock guards, and error-checked results out of the enclosing scope, which prevents accidental reuse-after-the-check bugs and name clashes. It pairs especially well with structured bindings, giving the canonical idiom if (auto [it, ok] = m.insert(...); ok) { ... }. C++20 later extends the same idea to range-based for loops.
C++17 if/switch initializer: if (init; cond) scopes a variable to the whole if/else (or switch), preventing scope pollution and reuse-after-check bugs; pairs naturally with structured bindings (if (auto [it,ok]=...; ok)).
The code
// pre-C++17: the variable leaks into the enclosing scopeauto it = m.find(key);if (it != m.end()) use(it->second);// 'it' still alive here, polluting scope
// C++17: init-statement scopes the variable to the if/elseif (auto it = m.find(key); it != m.end()) use(it->second);else handle_missing(); // 'it' visible in else too, gone afterWhat this lesson walks through
- 01Scope the temporary to the branch
- 02Why it matters
- 03Gotcha — the init var lives through else
- 04Interview framing
if (init; condition) and switch (init; condition) let you declare a variable whose scope is exactly the if/else (or switch) block. The variable is visible in both the then and else branches and destroyed at the end — no leakage into the surrounding scope, mirroring what for-loops always allowed.
See it animated — step by step, at your own pace
Unlock the full interactive walkthrough of C++17: if / switch With Initializer and 100+ animated C++ interview lessons.