Control Flow
Control Flow
Branching, loops, scope, and common flow-control patterns.
Control Flow
Branching, loops, scope, and common flow-control patterns.
if (score >= 90) {
grade = 'A';
} else if (score >= 80) {
grade = 'B';
} else {
grade = 'C';
}
switchswitch (token) {
case '+':
handle_add();
break;
case '-':
handle_subtract();
break;
default:
handle_unknown();
break;
}
for (int i = 0; i < 10; ++i) {
total += i;
}
while (!done) {
poll();
}
do {
read_again();
} while (retry);
forfor (const auto& item : items) {
std::cout << item << '\n';
}
break: exit the nearest loop or switchcontinue: skip to the next iterationreturn: leave the current functionif with initializerif (auto it = map.find(key); it != map.end()) {
use(it->second);
}
switch with enumsenum class State { idle, running, done };
Prefer enum class to avoid accidental implicit conversions.
constexpr iftemplate <typename T>
void print_kind(const T& value) {
if constexpr (std::is_integral_v<T>) {
std::cout << "integral: " << value << '\n';
} else {
std::cout << "other: " << value << '\n';
}
}
Use if constexpr in templates when a branch should disappear entirely for some types.
switch habitsswitch (state) {
case State::idle:
start();
break;
case State::running:
[[fallthrough]];
case State::paused:
resume();
break;
}
enum class inputs.++it.i < values.size().