C++ · Control structures
Selection Structure (if)
Trace scores 59, 60, 89 and 90 through condition boundaries, the first matching if/else if branch and independent if statements.
Practice this topic in the app Read the lesson in the app
Conditions and branches
In everyday life we often make judgments: if it rains, take an umbrella; otherwise do not. This is exactly what C++'s if statement does.
Basic form:
if (condition) {
// Run when the condition is true
} else {
// Run when the condition is false
}Multiple branches (else if):
if (score >= 90) {
cout << "excellent";
} else if (score >= 60) {
cout << "pass";
} else {
cout << "retry";
}Braces {} enclose a "code block". If there is only one statement, the braces can be omitted, but it is strongly recommended to always add braces to avoid misunderstanding.
else pairs with the nearest unmatched if in the same nested structure; braces can make the association clear.
switch branch: when you need to choose an operation based on discrete values of an integer or enumeration, you can use switch. case labels must be constant expressions, and default handles the case where none match. After a case, execution does not end automatically, so break is usually added; when multiple cases are intentionally made to share handling, the labels can be placed adjacent to each other.
Check the boundary, then the branch order
Assume scores from 0 to 100: 90 or more is excellent, and 60 or more passes. An if / else if chain executes only its first matching branch. A broader condition placed first can hide a later branch.
| Score | score >= 90 | score >= 60 (if needed) | Output |
|---|---|---|---|
| 59 | False | False | retry |
| 60 | False | True | pass |
| 89 | False | True | pass |
| 90 | True | Not checked | excellent |
First common error: using > 60 instead of >= 60 mishandles exactly 60. Second: placing if (score >= 60) before else if (score >= 90) prevents 90 from reaching the excellent branch. Two independent if statements can both execute; that differs from an if / else if chain.
Run and check: test both sides of each threshold
#include <iostream>
#include <initializer_list>
int main() {
for (int score : {59, 60, 89, 90}) {
if (score >= 90) { std::cout << "excellent\n"; }
else if (score >= 60) { std::cout << "pass\n"; }
else { std::cout << "retry\n"; }
}
}Predict all four output lines before running. The loop only repeats the check for four inputs.
Try before revealing each answer
If >= 60 becomes > 60, which of the four results changes?
60 changes from pass to retry; 59, 89 and 90 are unchanged.
If >= 60 is checked before else if >= 90, what does 95 output?
It outputs pass. The first branch matches, so later conditions are not checked.
If registration starts at age 12, use age > 12 or age >= 12? How would you test it?
Use age >= 12 and test 11, 12 and 13. This is a fictional boundary exercise, not an age rule for an actual contest.
Branching and switch examples
Example 1: Determine a score grade
#include <iostream>
using namespace std;
int main() {
int score;
cin >> score;
if (score >= 90) {
cout << "A" << endl;
} else if (score >= 80) {
cout << "B" << endl;
} else if (score >= 60) {
cout << "C" << endl;
} else {
cout << "D" << endl;
}
return 0;
}When 85 is input, 85>=90 is false, 85>=80 is true, so it outputs B, and subsequent branches are no longer checked.
Example 2: The trap of omitting braces in if
#include <iostream>
using namespace std;
int main() {
int x = 5;
if (x > 10)
cout << "big" << endl;
cout << "end" << endl; // This line always executes!
return 0;
}Without braces, if controls only the first statement immediately following it. "end" is output regardless of whether the condition is true or false; this is a big pitfall!
Example 3: switch merging identical handling
#include <iostream>
using namespace std;
int main() {
int day = 6;
switch (day) {
case 6:
case 7: cout << "weekend" << endl; break;
default: cout << "weekday" << endl;
}
}Assume day is 1 to 7, output weekend. 6 and 7 share one handling block; break prevents continuing to execute the following branches.
Tips
- The condition after if must be enclosed in parentheses; this is required syntax.
- An if without braces controls only the single statement immediately following it; multiple statements must have braces.
- else if is evaluated from top to bottom in order; once a condition holds, the corresponding block is executed and the remaining branches are skipped.
- else pairs with the nearest if (nearest-match principle); when nesting if-else, always use braces to make the levels clear.
- In conditions, use == for comparison (two equals signs); mistakenly writing = is assignment, and the logic is completely different.
Prerequisites
Technical references
Scope note
This lesson is written by InfoCode and is not an official syllabus; the reference level is a site mapping and does not represent official levels, certification or eligibility. Practice records do not establish mastery or eligibility.
Reference level: GESP Level 1 (site mapping)