C++ else if Statement
Introduction to else if
The else if pattern lets you test multiple conditions sequentially in one decision chain and execute only the first matching branch.
In C++, else if is not a single keyword—it's an else followed by a new if. This matters for how else binds (it attaches to the nearest preceding unmatched if).
Basic Syntax
The structure of an if, else if, and optional else block:
if (condition1) {
// code if condition1 is true
} else if (condition2) {
// code if condition2 is true
} else {
// code if all conditions are false
}Practical Example
This example assigns a grade based on score using an if-else if-else chain:
#include <iostream>
using namespace std;
int main() {
int score = 85;
if (score >= 90) {
cout << "Grade: A";
} else if (score >= 80) {
cout << "Grade: B";
} else if (score >= 70) {
cout << "Grade: C";
} else {
cout << "Grade: F";
}
return 0;
}Grade: B
Important Notes
- Conditions are evaluated from top to bottom in the chain.
- Only the block of the first true condition executes; subsequent branches are skipped.
- Order matters: place more specific/narrow conditions before broader ones.
- When comparing floating-point values, prefer ranges or tolerances instead of ==.
Common Pitfalls
- **Independent if vs else if:** Using multiple plain if statements allows multiple branches to run; use else if when branches are mutually exclusive.
- **Dangling else:** else binds to the nearest unmatched if. Always use braces to make intent explicit.
- **Assignment vs comparison:** Writing = instead of == compiles but changes the condition.
- **Boundary mistakes:** Ensure ranges are complete and non-overlapping (e.g., x >= 80 && x < 90).
// Wrong: two 'if's can both execute
if (score >= 80) cout << "B or better";
if (score >= 90) cout << "A"; // this may also run
// Right: mutually exclusive
if (score >= 90) {
cout << "A";
} else if (score >= 80) {
cout << "B";
}
// Dangling else risk without braces
if (a)
if (b)
doThing();
else
handleElse(); // binds to 'if (b)'
// Safer with braces
if (a) {
if (b) {
doThing();
} else {
handleElse();
}
}Alternatives & Tips
- For discrete integral/enum choices, consider switch for clarity and potential fallthrough control.
- Extract complex conditions into well-named boolean functions/variables to improve readability.
- Keep chains short; if logic grows, consider lookup tables or strategy objects.