4.1 — if: make a choice

📘 Chapter 4⏱ about 1 min read✍️ Beginner friendly
Read one box at a time. No rush.

Do it only if...#

An if statement runs code only when something is true.

C++
int temperature { 30 }; if (temperature > 25){    std::cout << "It's hot! Drink water.\n";}
Output
It's hot! Drink water.

If temperature were 20, nothing would print.

The shape of an if#

  • if = the keyword.
  • ( ... ) = the question (the condition). It must give true or false.
  • { ... } = the code that runs if the answer is true.

Using bools#

A bool variable can go straight into an if:

C++
bool hasKey { true }; if (hasKey){    std::cout << "The door opens.\n";}

if (hasKey) reads like English: "if has key".

Good habit

Always use { } after an if, even for one line. It prevents a nasty kind of mistake (see 4.4 — Common if mistakes).

Finished reading? Tick it off. Your progress is saved in this browser.

Tip: press ← / → to move between lessons, / to search.