If Statement
Until now, your programs ran every line, from top to bottom. Often you want some code to run only in some cases. The if statement does this. It runs a block of code only when a condition is true.
#include <iostream>
using namespace std;
int main() {
int age = 20;
if (age >= 18) {
cout << "You can vote" << "\n";
}
cout << "Done" << "\n";
return 0;
}
Output:
You can vote
Done
An if statement has three parts: the word if, a condition in parentheses, and a body in curly braces { }. The condition is a question with a true or false answer. The comparison operators from the Operators lesson, like >= and ==, give you exactly that.
Here age >= 18 is true, so the body runs. Now change age to 16:
int age = 16;
if (age >= 18) {
cout << "You can vote" << "\n";
}
cout << "Done" << "\n";
Output:
Done
The condition is false, so C++ skips the body. The Done line is outside the braces, so it runs in both cases.
Always write the braces
C++ lets you leave out the braces when the body is one line. Then the if controls only that one line. This causes bugs when you add a second line later:
int age = 16;
if (age >= 18)
cout << "You can vote" << "\n";
cout << "Welcome, voter" << "\n";
Output:
Welcome, voter
The indentation makes both lines look like part of the if. But C++ does not look at indentation. Only the first line belongs to the if, so the second line runs for a 16-year-old too. With braces, this cannot happen.
Use == to compare, not =
A single = puts a value into a variable. It does not compare. Look at what happens when you use it in a condition by mistake:
int age = 16;
if (age = 18) {
cout << "You can vote" << "\n";
}
cout << "age is now " << age << "\n";
Output:
You can vote
age is now 18
The program compiled with no error. age = 18 changed age to 18, and the whole age = 18 also has the value 18. C++ treats any number that is not 0 as true, so the body ran. To compare, write age == 18. When an if does something strange, check for this mistake first.
In the exercise, print a warning only when the temperature is above 30.