Learn C++
#include "controlflow/if_else.hpp"

if, else if, else Statements in C++

//concept

An if statement runs a block only when its condition is true; else if chains test alternatives in order and a trailing else catches everything left over. Conditions accept any expression convertible to bool — comparisons most often, but also direct bool variables, pointers (null means false), and stream states.

C++17 added if with initializer (if (int n = read(); n > 0)), which limits a helper variable's scope to the branch that needs it. Braces are optional for single statements but omitting them is a classic dangling-else bug farm — always brace.

//how it works
1

if runs on true

if (score >= 60) { ... } executes the block only when the comparison yields true; otherwise control skips past it.

2

else if chains alternatives

Each else if tests only when everything above failed, giving first-match-wins ordering for grades, ranges, and categories.

3

else catches the rest

A final else needs no condition — it runs whenever no earlier branch matched, guaranteeing some path executes.

4

Always use braces

Single-statement branches without braces invite dangling-else surprises when a line is added later — brace every branch unconditionally.

//example
#include <iostream>
 
int main() {
int score = 85;
if (score >= 90) {
std::cout << "A" << std::endl;
} else if (score >= 80) {
std::cout << "B" << std::endl;
} else {
std::cout << "C or below" << std::endl;
}
return 0;
}
Output
B
1score >= 90 is false for 85, so the first block is skipped entirely.
2score >= 80 is true, so B prints and the whole chain exits — the else never runs.
3Only one branch ever executes; the chain guarantees exactly one outcome.
//use cases
Grading, tiering, and range classification with ordered else-if chains
Validating input with early if (bad) branches before the real work
Scoping a helper with C++17 if-init so it can't leak past the branch
Guaranteeing a fallback path with a trailing else in parsers and menus

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Pro code editor & AI assistantWrite, debug and explain code faster while you practice the patterns here.Try it free Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books

Practice what you learned

Re-implement each visualized algorithm in C++ yourself — building beats watching.