Loading lessons...
Else If
Else If
Real life usually has more than two options. The else if chain checks several conditions in order.
The shape
if (condition1) {
// first choice
} else if (condition2) {
// second choice
} else {
// fallback when nothing matched
}
A time-of-day example
#include <iostream>
using namespace std;
int main() {
int hour = 14;
if (hour < 10) {
cout << "Good morning" << endl;
} else if (hour < 20) {
cout << "Good day" << endl;
} else {
cout << "Good evening" << endl;
}
return 0;
}
C++ works through the checks from top to bottom. With hour = 14, the first question (hour < 10) is false. The second question (hour < 20) is true, so "Good day" prints and the chain stops there.
Order matters
The computer stops at the first true condition, so placement decides which branch wins. Put the most specific checks first and keep the conditions in a sensible order, or an early broad condition will grab everything before the later ones get a turn.
With hour = 23, both branches fail until the final else catches it: "Good evening".
TL;DR
else ifchains let you check several conditions in order.- The first true condition wins, and the rest of the chain is skipped.
- Order matters: the earliest conditions grab the matches.
- A trailing
elsecatches every case that did not match.