Loading lessons...
If...Else
If...Else
Sometimes you want one thing when a condition is true, and something different when it is false. That is the job of the else branch.
The shape
if (condition) {
// runs when the condition is true
} else {
// runs when the condition is false
}
A time-of-day example
#include <iostream>
using namespace std;
int main() {
int time = 20;
if (time < 18) {
cout << "Good day." << endl;
} else {
cout << "Good evening." << endl;
}
return 0;
}
Here time is 20, so time < 18 is false. The else branch runs and prints "Good evening."
When does the else run?
Exactly whenever the if condition is false. The two branches are opposites:
- Condition true: the
ifblock runs. - Condition false: the
elseblock runs.
Never both, never neither
For any single if/else, exactly one of the two blocks runs. The program has no other path it can take.
TL;DR
if (condition) { ... } else { ... }gives two alternative paths.- The
elseblock runs only when the condition is false. - Exactly one branch runs each time.
- The
elsehandles the "everything else" cases.