Tip of the Week #165: if and switch statements with initializers
▻https://abseil.io/tips/165
Originally posted as TotW #165 on August 17, 2019
By Thomas Köppe
Updated 2020-01-17
Quicklink: abseil.io/tips/165
Unless you use conditional control flow, you can stop reading now.
A new syntax
C++17 allows if and switch statements to include an initializer:
if (init; cond) / ... / switch (init; cond) / ... /
This syntax lets you keep the scope of variables as tight as possible:
if (auto it = m.find("key"); it != m.end()) return it->second; else return absl::NotFoundError("Entry not found");
The semantics of the initializer are exactly as in the for statement; details below.
When this is useful
One of the most important ways to manage complexity is to break complex systems down into non-interacting, local parts that can be understood in isolation and ignored in their (...)