DevAcademia lesson/C++ Basics
else if Statement
Topic progressTopic 40 of 109 - 37% complete
~8 min lesson19 learning blocks3 code examples1 checks/interactions
Lesson outline
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:
Practical Example
This example assigns a grade based on score using an if-else if-else chain:
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
ifvselse if: Using multiple plainifstatements allows multiple branches to run; useelse ifwhen branches are mutually exclusive. - Dangling
else:elsebinds to the nearest unmatchedif. 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).
Alternatives & Tips
- For discrete integral/enum choices, consider
switchfor 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.
Was this topic clear?