Conditional Branching (if, else if, else)
Every program you’ve seen so far runs the same way, line one first, then line two, then line three, and so on. That’s fine for getting started, but programs also need to react to different situations. You need a way to tell the computer: “do this, but only if a specific condition is true.”
Conditional statements make that possible.
The basic if statement
Here’s a simple example. Say you’re writing a program that checks if someone is old enough to get a driver’s license:
The if keyword is followed by a condition in parentheses that evaluates to true or false. When it’s true, the code inside the curly braces runs. When it’s false, that block of code gets skipped entirely, and the program moves on to whatever comes after it.
Here, age is set to 17, so both messages print. Change it to 12, and the condition now evaluates to false, so the first message is skipped, and only “Moving on.” is printed.
Adding an else
Right now, the user gets no feedback when the age check fails. Usually you want to handle both outcomes explicitly. That’s what the else keyword is for:
With age = 12, the condition is false, so the if block is skipped and the else block runs instead. Change age back to 17 and the opposite happens. Either way, one of those two messages always prints.
Chaining conditions with else if
What if there’s a situation where two options aren’t enough? Like sorting a package into four different categories based on its weight.
Here, you’ll notice one if block, followed by two else if blocks, and a final else block. These checks are evaluated in sequence:
- With
weightInKg = 7.5, the first condition (<= 1.0) isfalse, so C++ moves to the next one. - The second condition (
<= 5.0) is alsofalse. - The third (
<= 10.0) istrue, so that branch runs, and the finalelseis never even reached.
The final else is optional
You don’t always need a final else. Sometimes it’s fine to do nothing if none of the conditions match.
That said, a trailing else is often a good defensive practice to explicitly handle all kinds of situations.
Braces are optional for single statements, but don’t skip them
If a branch has just one statement, C++ lets you drop the curly braces:
if (age >= 16) std::cout << "You're old enough to apply for a license.\n";This works fine. But it’s a common source of bugs, because it’s easy to add a second line later and forget that only the first line is actually part of the if statement:
if (age >= 16) std::cout << "You're old enough to apply for a license.\n"; std::cout << "Congratulations!\n"; // This always runsThat second std::cout line looks like it’s part of the if statement because of the indentation, but indentation means nothing to the compiler. So, the second line runs unconditionally.
Checkpoint
A weather station logs a temperature reading with this code, but it doesn’t work correctly. What’s the actual bug?
if (tempCelsius > 35.0) {
std::cout << "Heat warning.\n";
} else if (tempCelsius > 0.0) {
std::cout << "Normal range.\n";
} else if (tempCelsius < 0.0) {
std::cout << "Frost warning.\n";
}Two versions of a grading system are shown below. For every possible integer score, do they ever produce different output?
// Version A
if (score >= 90) {
std::cout << "A\n";
} else if (score >= 70) {
std::cout << "B or C\n";
} else if (score < 70) {
std::cout << "F\n";
}
// Version B
if (score >= 90) {
std::cout << "A\n";
} else if (score >= 70) {
std::cout << "B or C\n";
} else {
std::cout << "F\n";
}How many messages does this program print?
int orderTotal = 12;
if (orderTotal > 50)
std::cout << "Add a complementary item.\n";
std::cout << "Order confirmed.\n";
if (orderTotal <= 50)
std::cout << "Order confirmed.\n";