C++ Switch
The `switch` statement compares one value against multiple `case` labels, which is often clearer than a long if/else-if chain. Each case should end with `break` to prevent falling through to the next case.
switch only works with integral types (int, char, enum) and constant case labels โ it cannot switch on strings or floating-point values directly.
How switch works
The expression in `switch()` is compared to each `case` value; execution jumps to the matching label and continues until a `break` or the end of the switch.
Fall-through and default
Omitting `break` lets execution 'fall through' into the next case โ sometimes intentional but often a bug. `default` runs when no case matches.
int day = 3;
switch (day) {
case 1: std::cout << "Mon"; break;
case 3: std::cout << "Wed"; break;
default: std::cout << "Other";
}Wedday matches case 3, so 'Wed' is printed.
Key points
- switch compares a value against case labels.
- break prevents fall-through into the next case.
- default runs if no case matches.
- switch works only with integral/enum types.
