Making Decisions
8 min · C++
Run different code depending on whether something is true.
Enemy 1 of 5
if, else, and comparisons
Programs need to branch — do one thing in one situation and something else in another. C++'s if statement checks a condition inside parentheses, and if that condition evaluates to true, it runs the block of code in the { } that follows. If the condition is false, that block is skipped entirely.
An else block attached to an if runs only when the if's condition was false, giving you a clean "otherwise, do this" fallback. You can also chain else if between them to check several conditions in order, stopping at the first one that's true.
Comparisons use > (greater than), < (less than), >= and <= (greater/less than or equal), == (equal to), and != (not equal to). A very common beginner bug is writing a single = (assignment) where you meant == (comparison) — the compiler often won't catch this for you, so it's worth double-checking.
Loading editor...