if / else if / else
C++ uses if / else if / else to branch execution based on conditions. Since C++17, an initializer can be included inside the if statement to limit the scope of a variable to the block. This page covers basic conditional branching, nesting, and the ternary operator.
Syntax
// Executes the block when the condition is true
if (condition) {
// executed when true
}
// Provides an alternative when the condition is false
if (condition) {
// true branch
} else {
// false branch
}
// Evaluates multiple conditions in order
if (condition1) {
// condition1 is true
} else if (condition2) {
// condition2 is true
} else {
// none matched
}
// Nested if: combine conditions
if (conditionA) {
if (conditionB) {
// both A and B are true
}
}
// Initializer if (C++17): variable scope limited to the block
if (int result = getValue(); result > 0) {
// result is positive
}
// Ternary operator
int score = (syncRate >= 60) ? 1 : 0;
Syntax Reference
| Syntax / Operator | Description |
|---|---|
| if (condition) { } | Executes the block when the condition is non-zero (true). |
| if (...) { } else { } | Executes the else block when the condition is false. |
| if (...) { } else if (...) { } else { } | Evaluates conditions from top to bottom and executes the first matching branch. |
| Nested if | Placing an if inside another if block to express compound conditions. |
| if (init; condition) { } (C++17) | Declares a variable inside the if; its scope is limited to the block. |
| condition ? valueA : valueB | Ternary operator. Returns valueA when true, valueB when false. |
Sample Code
sync_rank.cpp
// sync_rank.cpp
// Evaluates sync rates of three NERV pilots.
// Demonstrates if / else if / else, nested if, initializer if (C++17), and ternary.
#include <iostream>
#include <string>
std::string getSyncRank(int rate) {
if (rate >= 400) {
return "Mythic War";
} else if (rate >= 100) {
return "Awakening";
} else if (rate >= 80) {
return "Rank A";
} else if (rate >= 60) {
return "Rank B";
} else if (rate >= 40) {
return "Rank C";
} else {
return "Needs Training";
}
}
int main() {
std::string pilots[] = { "Ikari Shinji", "Ayanami Rei", "Asuka Langley" };
int syncRates[] = { 400, 61, 98 };
int count = 3;
std::cout << "=== NERV Sync Rate Evaluation ===" << std::endl;
for (int i = 0; i < count; i++) {
// Initializer if (C++17): obtain rate and branch in one expression
if (int rate = syncRates[i]; rate >= 0) {
std::string rank = getSyncRank(rate);
std::string alert = (rate >= 400) ? " [EMERGENCY: Runaway Warning]" : "";
std::cout << pilots[i] << ": sync " << rate
<< "% → " << rank << alert << std::endl;
// Nested if: print additional message
if (rate < 40) {
if (i == 0) {
std::cout << " → Believe in yourself, Shinji." << std::endl;
} else {
std::cout << " → Additional training required." << std::endl;
}
}
}
}
return 0;
}
g++ -std=c++17 sync_rank.cpp -o sync_rank ./sync_rank === NERV Sync Rate Evaluation === Ikari Shinji: sync 400% → Mythic War [EMERGENCY: Runaway Warning] Ayanami Rei: sync 61% → Rank B Asuka Langley: sync 98% → Rank A
Common Mistake 1: Using = instead of == in a condition
Writing = (assignment) inside a condition instead of == (comparison) causes the assigned value to be evaluated. This usually does not produce a compile error, so extra attention is required.
// NG: hp = 0 is an assignment. The result (0 = false) is always evaluated.
if (hp = 0) {
std::cout << "Game Over" << std::endl;
}
OK: use == for comparison.
// OK:
if (hp == 0) {
std::cout << "Game Over" << std::endl;
}
Common Mistake 2: Overlapping else if ranges
else if is evaluated only when the preceding condition is false. If condition ranges overlap and a broader condition is placed first, the more specific condition is never reached.
// NG: rate >= 80 is never reached because rate >= 60 is evaluated first
if (rate >= 60) {
std::cout << "Rank B" << std::endl;
} else if (rate >= 80) {
std::cout << "Rank A" << std::endl; // unreachable
}
OK: place the stricter (larger) condition first.
// OK:
if (rate >= 80) {
std::cout << "Rank A" << std::endl;
} else if (rate >= 60) {
std::cout << "Rank B" << std::endl;
}
Overview
The if statement executes its block when the condition is non-zero (true). Chaining else if evaluates multiple conditions from top to bottom and runs only the first matching branch. If none match, the else block runs. Nested if statements combine conditions, but deep nesting can reduce readability; early returns or logical operators (&& / ||) are sometimes used to flatten the structure. The C++17 initializer if (if (init; condition)) declares a variable scoped to the block, making the intent clearer. The ternary operator (? :) expresses a simple binary choice in one line and is commonly used for concise expressions, though complex expressions may reduce readability.
If you find any errors or copyright issues, please contact us.