if, else if and else
An if runs its block only when the condition is true. Chain alternatives with else if; the first true branch wins and the rest are skipped. The condition can be any expression convertible to bool: numbers are true when non-zero, which is convenient and, as the error card below shows, occasionally dangerous.
#include <iostream>
int main() {
int scores[] = {95, 72, 58, 81};
for (int score : scores) {
char grade;
if (score >= 90) {
grade = 'A';
} else if (score >= 75) {
grade = 'B';
} else if (score >= 60) {
grade = 'C';
} else {
grade = 'F';
}
std::cout << score << " -> " << grade << '\n';
}
}95 -> A
72 -> C
58 -> F
81 -> BOrder matters: move the score >= 60 branch to the top and predict what every score gets before you run it.
Combining conditions
&& (and) and || (or) short-circuit: if the left side already decides the answer, the right side is never evaluated. That makes if (i < v.size() && v[i] > 0) safe, because the index is only used after it has been checked.
#include <iostream>
#include <vector>
bool loud(bool value, const char* name) {
std::cout << "checked " << name << '\n';
return value;
}
int main() {
std::vector<int> v{4, -2};
std::size_t i = 5;
if (i < v.size() && v[i] > 0) { // v[5] is never read
std::cout << "positive\n";
} else {
std::cout << "out of range or not positive\n";
}
if (loud(true, "left") || loud(false, "right")) {
std::cout << "or: done after the left side\n";
}
bool isAdmin = false, isOwner = true;
std::cout << std::boolalpha << (!isAdmin && isOwner) << '\n';
}out of range or not positive
checked left
or: done after the left side
trueusing the result of an assignment as a condition
#include <iostream>
int main() {
int stock = 0;
if (stock = 5) {
std::cout << "in stock\n";
}
}main.cpp:5:15: warning: using the result of an assignment as a condition without parentheses [-Wparentheses]
5 | if (stock = 5) {
| ~~~~~~^~~
main.cpp:5:15: note: place parentheses around the assignment to silence this warning
5 | if (stock = 5) {
| ^
| ( )
main.cpp:5:15: note: use '==' to turn this assignment into an equality comparison
5 | if (stock = 5) {
| ^
| ==A single = assigns 5 to stock, and the value of the assignment (5) is non-zero, so the condition is always true. The program compiles, runs and prints "in stock" even though the stock was 0. It is only a warning, so you see it only with -Wall.
Use == to compare. Building with -Wall -Werror turns this into a hard error so it can never ship.
#include <iostream>
int main() {
int stock = 0;
if (stock == 5) {
std::cout << "in stock\n";
}
}