2.2 Conditional Branches
Conditional branches let a program choose different code paths for different situations. C++ uses if, else if, and else for branching, and groups the statements that belong to a branch into a block with braces {}.
if
An if statement checks a condition. If the condition is true, C++ runs the block inside the braces. If the condition is false, C++ skips that block.
int age;
std::cin >> age;
if (age > 0 && age < 18) {
std::cout << "Minor" << std::endl;
}One possible run:
17
MinorIn C++, the statements that belong to an if go inside braces {}. Even for a single line, adding braces is recommended to avoid mistakes when the code grows later.
if-else
if-else is used for a two-way choice: run the if block when the condition is true; otherwise run the else block.
Here is a leap-year example. A year is a leap year if it satisfies one of these conditions:
- It is divisible by 4, and not divisible by 100.
- Or it is divisible by 400.
int year;
std::cin >> year;
bool is_leap_year = (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);
if (is_leap_year) {
std::cout << "Leap year" << std::endl;
} else {
std::cout << "Common year" << std::endl;
}One possible run:
2020
Leap yearSaving the complex condition into is_leap_year makes the if line easier to read. In real programs, this is often more maintainable than placing a long condition directly inside if.
if-else if-else
When there are more than two cases, use if-else if-else. C++ checks conditions from top to bottom. It runs the first branch whose condition is true, then skips the remaining branches.
char c;
std::cin >> c;
if (c >= 'a' && c <= 'z') {
std::cout << "Lowercase" << std::endl;
} else if (c >= 'A' && c <= 'Z') {
std::cout << "Uppercase" << std::endl;
} else if (c >= '0' && c <= '9') {
std::cout << "Digit" << std::endl;
} else {
std::cout << "Special character" << std::endl;
}One possible run:
T
UppercaseThe order of else if branches matters. Put more specific or higher-priority conditions earlier, and use else as the fallback case.