C++ Notes
else if.if (condition1) { // executes if condition1 is true } else if (condition2) { // executes if condition1 is false and condition2 is true } else { // executes if all above conditions are false }
int, char, enum.break to prevent fall-through into the next case.default runs if no case matches. It's the equivalent of a final else.break between them.switch (x) { case 1: // code break; case 2: // code break; case 3: // code break; default: // runs if no case matches break; }
case 1: case 2: case 3: { // executes for case 1, 2, or 3 } break;
The fall-through here is intentional. Cases 1, 2, and 3 all fall into the same block because none of them have a break before it, they just stack right into the shared code.
if-else.result = condition ? option1 : option2; // if condition is true -> expression evaluates to option1 // if condition is false -> expression evaluates to option2
cout: std::cout << (x > y ? x : y) << '\n'; prints the larger value.int a = x > y ? x : y; assigns the larger value to a.Always wrap ternary expressions in parentheses () when using them inside cout. Without them, the << operator may get parsed before ? and cause unexpected behavior.
#include <iostream> int main() { int a{10}, b{20}, c{30}, d{40}; // largest of 3: check a vs b first, then winner vs c std::cout << "Largest of 3: " << (a>b ? (a>c ? a : c) : (b>c ? b : c)) << '\n'; // prints: 30 // largest of 4: same idea extended one level deeper std::cout << "Largest of 4: " << (a>b ? (a>c ? (a>d ? a : d) : (c>d ? c : d)) : (b>c ? (b>d ? b : d) : (c>d ? c : d))) << '\n'; // prints: 40 return 0; }
| Situation | Use |
|---|---|
| A handful of distinct conditions, possibly ranges or compound logic | if / else if / else |
| One variable checked against many exact, discrete values (int, char, enum) | switch |
| Picking between exactly two values to use immediately, in an assignment or a print statement | Ternary |
Switch only reads clean when the values are genuinely discrete and few. The moment you need a range check like x > 10, switch can't express it at all, that's exactly the signal to reach for if-else instead.
That covers every branching tool C++ gives you: the flexible one, the discrete-value one, and the compact one. Next up, the three ways to repeat something.