C++ If..Else
Conditional statements let your program make decisions: run one block of code when a condition is true and (optionally) another when it is false.
The if statement
#include <iostream>
using namespace std;
int main() {
int battery = 15;
if (battery < 20) {
cout << "Low battery! Please charge.\n";
}
cout << "Battery: " << battery << "%\n";
}Low battery! Please charge.
Battery: 15%
The condition goes in parentheses and must produce something convertible to bool. If it is false, the block is skipped.
else and else if
else handles the "otherwise" case. To test several conditions in order, chain them with else if. Only the first matching branch runs:
#include <iostream>
using namespace std;
int main() {
int scores[] = {95, 82, 67, 40};
for (int score : scores) {
char grade;
if (score >= 90) {
grade = 'A';
} else if (score >= 75) {
grade = 'B';
} else if (score >= 50) {
grade = 'C';
} else {
grade = 'F';
}
cout << score << " -> " << grade << "\n";
}
}95 -> A
82 -> B
67 -> C
40 -> F
The order matters: if score >= 50 were tested first, a score of 95 would get a C.
Nested conditions
An if can live inside another if. Keep nesting shallow — two levels is usually the limit for readable code:
#include <iostream>
using namespace std;
int main() {
int age = 16;
bool withParent = true;
if (age >= 18) {
cout << "Entry allowed\n";
} else {
if (withParent) {
cout << "Entry allowed with a parent\n";
} else {
cout << "Entry denied\n";
}
}
}Entry allowed with a parent
The ternary operator
For a simple "choose one of two values", the conditional operator condition ? a : b is shorter than a full if/else:
#include <iostream>
#include <string>
using namespace std;
int main() {
int n = 7;
string kind = (n % 2 == 0) ? "even" : "odd";
cout << n << " is " << kind << "\n";
int items = 1;
cout << items << (items == 1 ? " item" : " items") << "\n";
}7 is odd
1 item
if with an initializer (C++17)
You can declare a variable that only exists for the if statement. It keeps the outer scope tidy:
#include <iostream>
#include <string>
using namespace std;
int main() {
string path = "report.pdf";
if (auto dot = path.find('.'); dot != string::npos) {
cout << "Extension: " << path.substr(dot + 1) << "\n";
} else {
cout << "No extension\n";
}
// 'dot' does not exist here
}Extension: pdf
Tip: Always use braces
{ }, even for a single statement. Without them only the next statement belongs to theif, and adding a second line later silently changes the program's meaning.
Test yourself
With x = 10, which branch runs? if (x > 5) A else if (x > 8) B else C
- A
- B
- A and B
- C
What does (3 > 4) ? "yes" : "no" evaluate to?
- "yes"
- "no"
- false
- 3
In if (int n = f(); n > 0) {...}, where can n be used?
- Everywhere in the function
- Only inside the if/else statement
- Only before the if
- Nowhere, it is a syntax error