C++ If…Else
An if...else statement lets a C++ program choose between different blocks of code. The program tests a condition, then runs the block that matches the result.
Conditions are boolean expressions, so they evaluate to either true or false. You can use comparisons such as score >= 70 inside the parentheses.
The if Statement
The simplest decision uses only if. The code inside the braces runs only when the condition is true.
#include <iostream>
int main(void) {
int score = 82;
if (score >= 70) {
std::cout << "You passed." << std::endl;
}
return 0;
}
Output:
You passed.
Adding else
Use else when you want one block to run if the condition is true and another block to run if it is false. The else block does not have its own condition.
#include <iostream>
int main(void) {
int age = 16;
if (age >= 18) {
std::cout << "You can vote." << std::endl;
} else {
std::cout << "You are too young to vote." << std::endl;
}
return 0;
}
Output:
You are too young to vote.
Testing Multiple Conditions
Use else if when there are more than two possible paths. C++ checks the conditions from top to bottom and runs the first matching block. After one block runs, the rest of the chain is skipped.
#include <iostream>
int main(void) {
int score = 76;
if (score >= 90) {
std::cout << "Grade: A" << std::endl;
} else if (score >= 80) {
std::cout << "Grade: B" << std::endl;
} else if (score >= 70) {
std::cout << "Grade: C" << std::endl;
} else {
std::cout << "Grade: Not passing" << std::endl;
}
return 0;
}
Output:
Grade: C
Syntax
The parentheses after if or else if hold the condition. The braces hold the statements that belong to that branch. The final else is optional, but it is useful when you need a default action.
A common layout is if first, then any else if branches, then one optional else branch at the end.
Using Logical Operators
You can combine conditions with logical operators. Use && when both conditions must be true, || when at least one condition must be true, and ! to reverse a condition.
#include <iostream>
int main(void) {
int temperature = 72;
bool raining = false;
if (temperature >= 65 && !raining) {
std::cout << "Good day for a walk." << std::endl;
} else {
std::cout << "Stay inside for now." << std::endl;
}
return 0;
}
Output:
Good day for a walk.
Common Mistakes
- Using
=when you meant==. The single equals sign assigns a value. - Forgetting braces around a branch that has more than one statement.
- Putting a semicolon right after the condition, such as
if (score >= 70);. That ends theifstatement too early. - Writing conditions in the wrong order. In a grade example, test higher scores before lower scores.
Takeaway: if, else if, and else let your program choose a path based on true-or-false conditions.
