Making Decisions
8 min · C++
Run different code depending on whether something is true.
Enemy 1 of 5
if, else, and comparisons
This code checks if temperature is greater than 20 and prints Warm if so, otherwise Cold. Since temperature is 5, the else part runs. Press Run to see Cold.
Why this works
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.