if, else if & else
Basic forms
if (condition) {
...
}
if (condition) {
...
} else {
...
}
if (score >= 90) { grade = 'A'; }
else if (score >= 75) { grade = 'B'; }
else if (score >= 50) { grade = 'C'; }
else { grade = 'F'; }
Conditions are checked top to bottom; the first true one runs and the rest are skipped. Order matters!
Always use braces ✅
if (x > 0)
std::cout << "positive\n";
count++; // NOT part of the if! (misleading indentation)
Nested ifs
if (logged_in) {
if (is_admin) { ... } else { ... }
}
Too much nesting? Use early returns or combine conditions with &&.
if with an initializer (C++17)
if (auto pos = email.find('@'); pos != std::string::npos) {
// pos is only visible inside this if/else
}
Keeps temporary variables in the smallest scope.
if constexpr (C++17)
Chooses a branch at compile time — used in templates (Unit 12).
Truthiness
Numbers: 0 is false, anything else true. Pointers: nullptr is false.
if (count) means if (count != 0).
Comparing doubles and strings
- doubles: use a tolerance (lesson 2.6)
std::stringcompares with==✅ (unlike C'sstrcmp)
Dangling else
else always belongs to the nearest unmatched if — another reason to use braces.
Example
#include <iostream>
#include <string>
char grade_for(int score) {
if (score >= 90) return 'A';
else if (score >= 75) return 'B';
else if (score >= 50) return 'C';
else return 'F';
}
void check_budget(double spent, double limit) {
if (limit <= 0) {
std::cout << " Invalid budget\n";
return; // early return keeps nesting low
}
double used = spent / limit * 100;
if (used > 100) {
std::cout << " Over budget by Rs. " << spent - limit << "!\n";
} else if (used >= 80) {
std::cout << " Careful: " << used << "% used\n";
} else {
std::cout << " On track: " << used << "% used\n";
}
}
int main() {
for (int s : { 95, 78, 50, 32 })
std::cout << "score " << s << " -> grade " << grade_for(s) << '\n';
std::cout << "Food budget:\n";
check_budget(4500, 5000);
std::cout << "Travel budget:\n";
check_budget(6200, 5000);
std::cout << "Fun budget:\n";
check_budget(1000, 0);
std::string email = "ravi@example.com";
if (auto at = email.find('@'); at != std::string::npos) { // C++17 if-with-initializer
std::cout << "Username: " << email.substr(0, at) << '\n';
} else {
std::cout << "Not an email\n";
}
int unread = 3;
if (unread) std::cout << "You have " << unread << " new messages\n";
return 0;
}
/* Output:
score 95 -> grade A
score 78 -> grade B
score 50 -> grade C
score 32 -> grade F
Food budget:
Careful: 90% used
Travel budget:
Over budget by Rs. 1200!
Fun budget:
Invalid budget
Username: ravi
You have 3 new messages
*/