Control Flow and Functions
Control Flow and Functions
Use `if`, loops, and reusable functions to organize program behavior.
Control Flow and Functions
Use `if`, loops, and reusable functions to organize program behavior.
ifif (temperature > 30) {
std::cout << "Hot\n";
} else {
std::cout << "Not hot\n";
}
for (int i = 1; i <= 5; ++i) {
std::cout << i << '\n';
}
int square(int x) {
return x * x;
}
#include <iostream>
bool is_even(int value) {
return value % 2 == 0;
}
int main() {
for (int i = 1; i <= 10; ++i) {
if (is_even(i)) {
std::cout << i << " is even\n";
}
}
}
#include <iostream>
#include <vector>
bool passed(int score) {
return score >= 50;
}
int count_passes(const std::vector<int>& scores) {
int total = 0;
for (int score : scores) {
if (passed(score)) {
++total;
}
}
return total;
}
void print_summary(const std::vector<int>& scores) {
std::cout << "passed: " << count_passes(scores) << '\n';
}
int main() {
std::vector<int> scores{48, 77, 90, 31, 64};
print_summary(scores);
}
This is the point of functions: main() reads like a summary, while smaller helpers carry the details.
bool is_valid_score(int score) {
if (score < 0) {
return false;
}
if (score > 100) {
return false;
}
return true;
}
This is usually easier to read than wrapping the whole function body in nested if blocks.
switch and enum classenum class MenuChoice { add, remove, quit };
void handle(MenuChoice choice) {
switch (choice) {
case MenuChoice::add:
add_item();
break;
case MenuChoice::remove:
remove_item();
break;
case MenuChoice::quit:
shutdown();
break;
}
}
This keeps control flow readable when the set of cases is closed and explicit.
int and double by value.const&.switch is better than ifUse switch when the set of cases is closed and tied to one value, such as a menu choice, token kind, or state enum. Use if chains when the conditions are ranges, combinations, or unrelated predicates.
Refactor a loop-heavy program into three functions: input, computation, and output. The goal is to make main() read like a summary of the program.
int square(int value) {
return value * value;
}
int main() {
for (int i = 0; i < 3; ++i) {
if (square(i) == 1) {
return 0;
}
}
}
Turn the loop condition into a named helper that returns `bool`. That is usually the point where functions start improving readability instead of just splitting code apart.
bool should_stop(int value) {
return value * value >= 4;
}
int main() {
for (int i = 0; i < 5; ++i) {
if (should_stop(i)) {
break;
}
}
}