C++ else Statement
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.
if (condition) {
// code executes if condition is true
} else {
// code executes if condition is false
}
Practical Example
This program checks the temperature and chooses between two possible outputs.
#include <iostream>
using namespace std;
int main() {
int temperature = 25;
if (temperature > 30) {
cout << "It's hot outside";
} else {
cout << "It's not too hot";
}
return 0;
}
It's not too hot
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.
// Problematic: stray semicolon => empty 'then' statement
if (isReady); // null statement
else {
handleNotReady(); // executes whenever program reaches here
}
// Safer, explicit structure
if (isReady) {
proceed();
} else {
handleNotReady();
}
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
if (fileExists) {
openFile();
} else {
cout << "Error: File not found";
}
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 if
or else
block are local to that block.
- **Prefer early returns:** In functions, an early return
can reduce nesting and sometimes eliminate the need for an else
.
// Early return to reduce nesting
bool save(User u) {
if (!u.isValid()) {
return false; // no else needed
}
return doSave(u);
}
Alternative: Ternary Operator
For simple value selection, use the conditional (ternary) operator to keep expressions concise.
int age = 20;
string access = (age >= 18) ? "adult" : "minor"; // expression-level alternative to if/else