C++ If ... Else
The if statement runs code only when a condition is true. With else and else if, a program chooses between several paths.
if, else if, else
#include <iostream>
int main() {
int marks;
std::cout << "Marks (0-100): ";
std::cin >> marks;
if (marks >= 90) {
std::cout << "Grade A\n";
} else if (marks >= 75) {
std::cout << "Grade B\n";
} else if (marks >= 50) {
std::cout << "Grade C\n";
} else {
std::cout << "Grade D\n";
}
return 0;
}78
Marks (0-100): Grade B
Conditions are checked from the top, and the first true one wins. Order them from the most specific to the most general. Always write the braces, even for one statement: adding a second line later then cannot slip outside the if.
Combining conditions
#include <iostream>
int main() {
int age = 15;
bool hasTicket = true;
if (age >= 12 && hasTicket) {
std::cout << "You may enter.\n";
}
if (age < 13 || age > 64) {
std::cout << "Reduced price.\n";
} else {
std::cout << "Full price.\n";
}
return 0;
}You may enter. Full price.
The conditional operator
condition ? a : b chooses between two values in one expression:
#include <iostream>
#include <string>
int main() {
int n = 7;
std::string kind = (n % 2 == 0) ? "even" : "odd";
std::cout << n << " is " << kind << "\n";
return 0;
}7 is odd
if with an initializer (C++17)
C++17 lets an if declare a variable that exists only inside the if and its else, keeping it close to where it is used:
#include <iostream>
#include <string>
int main() {
std::string text = "hello world";
if (auto pos = text.find(' '); pos != std::string::npos) {
std::cout << "first word: " << text.substr(0, pos) << "\n";
} else {
std::cout << "one word only\n";
}
return 0;
}first word: hello
Common mistakes
- **
=instead of==**:if (x = 5)stores 5 and is always true. With-Wallthe compiler warns. - A semicolon after the condition:
if (x > 5);ends theifright there, and the block below always runs. - **Wrong order of
else iftests**: the first true test wins, so put the most specific test first. - Testing a range like in maths:
if (10 < x < 20)is always true in C++. Writeif (x > 10 && x < 20). - Deep nesting: several
ifstatements inside each other are hard to read. Returning early from a function (if (!valid) return;) often keeps the code flat.
Good practice
Keep conditions short and give complicated ones a name: bool canEnter = hasTicket && age >= 12; followed by if (canEnter) reads better than a long expression in the if. Handle the unusual case first and the normal case after it, so the main path of the code is easy to follow.
Practice exercises
- Read a year and print whether it is a leap year (divisible by 4, not by 100 unless by 400).
- Read three numbers and print the largest.
- Read a temperature and print "cold", "pleasant" or "hot".