else Statement
Lesson outline
Introduction to else
The else statement defines an alternative block of code that runs when the if condition evaluates to false (after implicit conversion to bool).
It lets programs handle both outcomes of a binary decision without leaving one case unspecified.
Basic Syntax
The else statement follows an if and executes only if the if condition is false. Always use braces for clarity.
Practical Example
This program checks the temperature and chooses between two possible outputs.
Dangling else & Stray Semicolons
In C++, else binds to the nearest preceding unmatched if. A stray semicolon after if (cond) creates an empty then-statement and can make the else run unconditionally.
Use braces to make intent explicit and avoid the classic dangling-else trap.
Common Patterns
The else clause is widely used for:
- Error handling when conditions fail
- Providing default behavior when no other conditions are met
- Representing binary choices in decision-making
Pitfalls & Tips
- Assignment vs comparison:
if (x = 0)assigns 0 and tests false; use==for comparison. - Side effects in conditions: Keep conditions simple; avoid function calls with side effects that make control flow hard to reason about.
- Branch scope: Variables declared inside the
iforelseblock are local to that block. - Prefer early returns: In functions, an early
returncan reduce nesting and sometimes eliminate the need for anelse.
Alternative: Ternary Operator
For simple value selection, use the conditional (ternary) operator to keep expressions concise.