4.1 — if: make a choice
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 givetrueorfalse.{ ... }= the code that runs if the answer istrue.
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).
Tip: press ← / → to move between lessons, / to search.