if and else
At the end of each run, Rocket Run hands out a medal: Gold for 1000 points or more, Silver for 500 or more, Bronze for everything else. Three outcomes, one score, and the order in which you ask the questions decides whether the medals come out right.
The rule
The first true condition wins; every later branch is skipped.
std::string medal;
if (score >= 1000) {
medal = "Gold";
} else if (score >= 500) {
medal = "Silver";
} else {
medal = "Bronze";
}C++ checks the conditions top to bottom. As soon as one is true, it runs that block and jumps past the rest of the chain. The final else catches anything that matched nothing.
Useful extras:
- The ternary operator chooses between two values in one expression:
std::string status = lives > 0 ? "alive" : "game over"; - An initializer inside
if(C++17) keeps a helper variable local to the decision:
if (int bonus = coins / 100; bonus > 0) {
lives += bonus;
} // bonus no longer exists here- A condition can be any value that converts to
bool: zero is false, any other number is true.
Always use braces, even for one line. It prevents the classic bug where a second line looks like it belongs to the if but does not.
The shortcut
Order the tests from the strictest to the loosest. Then walk a value down the chain and stop at the first yes.
First test
750 >= 1000? No. Move on.
The second trap is = in place of ==. if (lives = 0) compiles: it assigns 0 to lives, and then tests 0, which is false. Compile with -Wall and the compiler will warn you.
Drills
Answer fast — trust the rule.
The chain tests score >= 500 (Silver) before score >= 1000 (Gold). What does 1200 get?
What does if (lives = 0) { ... } do?
With lives equal to 0, what does lives > 0 ? "alive" : "game over" produce?
In if (int bonus = coins / 100; bonus > 0) { ... } else { ... }, where can bonus be used?
Remember
- The first true condition wins; every later branch is skipped.
- Shortcut: order tests from strictest to loosest.
- Trap:
=assigns,==compares;-Wallcatches the mix-up.
