Skip to the workspace
Pebellslearn by building
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.

cpp / if and else

Explore each scene at your own pace.

01 · The rule

The rule

if and else

An if and else-if chain tests its conditions from top to bottom and runs only the first branch whose condition is true.

Trace nested decisions and make the intended branch boundaries explicit.

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.

Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.