C++ If...Else
The `if`, `else if`, and `else` statements let a program branch based on conditions. The condition inside `()` must evaluate to something convertible to bool.
C++17 also introduced the ternary operator `condition ? valueIfTrue : valueIfFalse`, a compact way to write simple if/else assignments.
if / else if / else
Conditions are checked top to bottom; the first true branch runs and the rest are skipped. `else` catches everything not matched above.
Ternary operator
`int max = (a > b) ? a : b;` picks a or b depending on the condition, without writing a full if/else block.
int age = 20;
if (age >= 18) {
std::cout << "Adult";
} else {
std::cout << "Minor";
}AdultThe condition age >= 18 is true, so the first branch runs.
int a = 5, b = 9;
int m = (a > b) ? a : b;
std::cout << m;9The ternary operator picks the larger value.
Key points
- if/else if/else branch based on a condition.
- Only the first matching branch executes.
- The ternary operator ?: is a compact if/else.
- Conditions must be convertible to bool.
