Codiqo

Learn C++ · lesson 15 of 61 · about 8 minutes

else if and Nesting

Fight a goblin: choose between several outcomes with else if, catch impossible values first, and put decisions inside decisions.

What you'll learn

  • Chain conditions with else if
  • Order conditions correctly
  • Nest if statements

More than two outcomes

A goblin jumps out, and the hero rolls a die: 5 or 6 beats it, 3 or 4 scares it off, and 1 or 2 means it bites. That's three outcomes, and if with else only gives two.

else if adds more conditions. They're checked from the top, only the first true branch runs, and else catches whatever is left.

The goblin fight

#include <iostream>

int main() {
    int roll = 4;
    if (roll >= 5) {
        std::cout << "You beat the goblin!\n";
    } else if (roll >= 3) {
        std::cout << "The goblin runs away.\n";
    } else {
        std::cout << "The goblin bites you.\n";
    }
}

Output

The goblin runs away.

Order matters

Check in one direction. Here that's the highest roll first: if roll >= 3 came first, a 6 would match it and the goblin would only run away. And check impossible values before anything else: a die only shows 1 to 6, so roll < 1 || roll > 6 goes at the top.

A decision inside a decision

#include <iostream>

int main() {
    bool hasTorch = true;
    bool hasMap = false;
    if (hasTorch) {
        if (hasMap) {
            std::cout << "You find the way out.\n";
        } else {
            std::cout << "You can see, but you're lost.\n";
        }
    } else {
        std::cout << "It's too dark to move.\n";
    }
}

Output

You can see, but you're lost.

Tip

C++ has no elif: it's two words, else if.

Now try it yourself

This lesson is free in Codiqo, with 9 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.