if, else if, else Statements in C++
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.
if runs on true
if (score >= 60) { ... } executes the block only when the comparison yields true; otherwise control skips past it.
else if chains alternatives
Each else if tests only when everything above failed, giving first-match-wins ordering for grades, ranges, and categories.
else catches the rest
A final else needs no condition — it runs whenever no earlier branch matched, guaranteeing some path executes.
Always use braces
Single-statement branches without braces invite dangling-else surprises when a line is added later — brace every branch unconditionally.
#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;}Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Practice what you learned
Re-implement each visualized algorithm in C++ yourself — building beats watching.