C++ ยท Chapter 15 of 49

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.

Example 1 (cpp)
int age = 20;
if (age >= 18) {
    std::cout << "Adult";
} else {
    std::cout << "Minor";
}
Output
Adult

The condition age >= 18 is true, so the first branch runs.

Example 2 (cpp)
int a = 5, b = 9;
int m = (a > b) ? a : b;
std::cout << m;
Output
9

The 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.
๐Ÿ’ก Note: Always wrap multi-statement branches in {} โ€” a missing brace after if is a classic bug source.

๐Ÿ“ Quick Quiz

1. Which keyword provides a fallback branch?

2. What does the ternary operator look like?

3. How many branches run in an if/else if/else chain?