Codiqo

Learn C++ · lesson 14 of 61 · about 7 minutes

if and else

Let the guard's answer change the story: run code only when a condition is true, give an alternative with else, and keep every branch in braces.

What you'll learn

  • Write an if statement
  • Add an else branch
  • Use braces for every branch

Doing something about it

The guard has decided, and letIn holds the answer, but the story doesn't change yet. if (condition) { ... } runs its block only when the condition is true, and else { ... } runs otherwise. The condition goes in round brackets, and each block goes in braces.

The gate opens, or it doesn't

#include <iostream>

int main() {
    bool letIn = false;
    int health = 85;
    if (letIn) {
        std::cout << "You step out into the sunlight.\n";
    } else {
        health -= 10;
        std::cout << "The guard shoves you back. Health: " << health << "\n";
    }
    std::cout << "The story goes on.\n";
}

Output

The guard shoves you back. Health: 75
The story goes on.

Always use braces

Without braces, an if only guards the one statement after it. Indenting a second line doesn't put it inside: C++ ignores indentation. Worse, an else after two unbraced lines doesn't compile at all, because the if already ended. Braces on every branch avoid both problems, even when a branch is one line long.

Tip

In a condition, 0 counts as false and any other number as true, so if (gold) means "if gold isn't 0".

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.