Pebellslearn by building
0%
RoadmapsMatrixCoursesSandboxSign in
Control Flow and Statements  ›  Lesson

if and else

if else / switch / goto 12 minAn if and else-if chain tests its conditions from top to bottom and runs only the first branch whose condition is true.

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.

Which medal for 750 points?Step 1 of 4
  1. 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.

quick drill

The chain tests score >= 500 (Silver) before score >= 1000 (Gold). What does 1200 get?

quick drill

What does if (lives = 0) { ... } do?

quick drill

With lives equal to 0, what does lives > 0 ? "alive" : "game over" produce?

quick drill

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; -Wall catches the mix-up.

Practice — level up

0/1 solved

Write your answer, then compare it with a rubric and a model answer.

ExplainThe wrong medal

Rocket Run gives medals: 1000 or more is Gold, 500 or more is Silver, anything else is Bronze. A teammate checks score >= 500 first and score >= 1000 second, and a player with 1200 points gets Silver. Explain why and fix the chain.