Lesson 62 +10 XP

If Statements

If Statements

Sometimes you want code to run only when something is true. The if statement does exactly that.

The shape

if (condition) {
  // do this when the condition is true
}
  • Start with the keyword if.
  • The condition goes inside parentheses.
  • Then comes a block wrapped in curly braces { }.

A first example

#include <iostream>
using namespace std;

int main() {
  if (20 > 18) {
    cout << "20 greater than 18" << endl;
  }
  return 0;
}

The condition 20 > 18 is true, so the block runs and prints the message.

The condition is a boolean

The condition is usually a comparison that gives true or false. If it is true, the block runs. If it is false, the whole block is skipped.

if (5 > 8) {
  cout << "Never prints" << endl;
}

Blocks group statements

LearnCpp 8.2 reminds us that the block { } groups statements together so they all run as one unit. Every statement between the braces belongs to the if.

TL;DR

  • if (condition) { ... } runs the block only when the condition is true.
  • The condition is a boolean expression.
  • The block groups the statements that run together.
  • When the condition is false, the whole block is skipped.