Modern C++ • C++20 baseline
Branching with if, switch, and Scoped Variables
Select behavior with explicit conditions and keep branch-local state scoped narrowly.
if handles general conditions, while switch is useful for a fixed set of discrete values. C++ lets a switch case declare variables, but braces are often needed to give those variables a clear scope and avoid jumping across initialization. Prefer exhaustive handling when a type represents a finite set of states.
Key points
- Use braces for branches even when they contain one statement.
- A switch over an enum can make state handling easier to audit.
Example
#include <iostream>
enum class Mode { preview, publish };
int main() {
const Mode mode = Mode::preview;
switch (mode) {
case Mode::preview:
std::cout << "Preview\n";
break;
case Mode::publish:
std::cout << "Publish\n";
break;
}
}
What to expect
Preview
Practice exercise
Add a third enum value and make the switch handle it intentionally.
Key idea: Make each possible state visible in control flow, and avoid accidental fall-through.