> For the complete documentation index, see [llms.txt](https://alham-rizvi.gitbook.io/alhamrizvi/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://alham-rizvi.gitbook.io/alhamrizvi/c++-notes/12.-switch-statements.md).

# 12. Switch Statements

A `switch` compares one variable against several possible constant values (`case`s) and runs the matching block. It's often a cleaner alternative to a long `else if` chain.

```cpp
#include <iostream>

int main() {
    int day;
    std::cout << "Enter day number (1-7): ";
    std::cin >> day;

    switch (day) {
        case 1:
            std::cout << "Monday\n";
            break;
        case 2:
            std::cout << "Tuesday\n";
            break;
        case 3:
            std::cout << "Wednesday\n";
            break;
        default:
            std::cout << "Some other day\n";
            break;
    }

    return 0;
}
```

***

### Structure

| Part                | Meaning                                                                                                               |
| ------------------- | --------------------------------------------------------------------------------------------------------------------- |
| `switch (variable)` | The value being tested.                                                                                               |
| `case value:`       | A possible match — if `variable == value`, this block runs.                                                           |
| `break;`            | Stops the switch here. **Without it, execution "falls through"** into the next case, even if that case doesn't match. |
| `default:`          | Runs if nothing else matched — the `switch` equivalent of a final `else`.                                             |

***

### ⚠️ The #1 beginner trap: forgetting `break`

Without `break`, C++ keeps executing every case **below** the matching one, regardless of whether it matches.

```cpp
#include <iostream>

int main() {
    int num = 1;

    switch (num) {
        case 1:
            std::cout << "one\n";   // this runs...
        case 2:
            std::cout << "two\n";   // ...and so does this (fall-through!)
        case 3:
            std::cout << "three\n"; // ...and this too
            break;
        default:
            std::cout << "other\n";
    }

    return 0;
}
```

**Output (missing `break`s):**

```
one
two
three
```

Add `break;` after each case to stop this:

```cpp
switch (num) {
    case 1:
        std::cout << "one\n";
        break; // stops here
    case 2:
        std::cout << "two\n";
        break;
    case 3:
        std::cout << "three\n";
        break;
    default:
        std::cout << "other\n";
}
```

> Fall-through isn't always a bug though — sometimes it's used on purpose, to let multiple cases share one block (see example 3 below).

***

### `switch` only works with integral types

`switch` works with `int`, `char`, `enum`, and similar whole-number-like types. It does **not** work with `std::string`.

```cpp
std::string color = "red";

switch (color) { // ❌ compile error: cannot switch on a std::string
    case "red":
        // ...
}
```

For string-based branching, you're stuck with `if / else if` chains — or, for a fixed set of named options, `enum` is a cleaner fit (covered in a later topic).

```cpp
// ✅ works: string comparison via if/else
if (color == "red") {
    std::cout << "Stop\n";
}
else if (color == "green") {
    std::cout << "Go\n";
}
```

***

### More cool examples

#### 1. A calculator using `switch`

```cpp
#include <iostream>

int main() {
    double num1, num2;
    char op;

    std::cout << "Enter calculation (e.g. 5 + 3): ";
    std::cin >> num1 >> op >> num2;

    double result = 0;

    switch (op) {
        case '+':
            result = num1 + num2;
            break;
        case '-':
            result = num1 - num2;
            break;
        case '*':
            result = num1 * num2;
            break;
        case '/':
            result = num1 / num2;
            break;
        default:
            std::cout << "Invalid operator\n";
            return 1;
    }

    std::cout << "Result: " << result << '\n';

    return 0;
}
```

#### 2. Grade lookup with `char`

```cpp
#include <iostream>

int main() {
    char grade;
    std::cout << "Enter your grade (A-D, F): ";
    std::cin >> grade;

    switch (grade) {
        case 'A':
            std::cout << "Excellent!\n";
            break;
        case 'B':
            std::cout << "Good job\n";
            break;
        case 'C':
            std::cout << "You passed\n";
            break;
        case 'D':
            std::cout << "Barely made it\n";
            break;
        case 'F':
            std::cout << "Better luck next time\n";
            break;
        default:
            std::cout << "Not a valid grade\n";
    }

    return 0;
}
```

#### 3. Intentional fall-through — grouping cases together

Multiple `case`s can share one block by stacking them with no `break` in between:

```cpp
#include <iostream>

int main() {
    int month;
    std::cout << "Enter month number (1-12): ";
    std::cin >> month;

    switch (month) {
        case 12:
        case 1:
        case 2:
            std::cout << "Winter\n";
            break;
        case 3:
        case 4:
        case 5:
            std::cout << "Spring\n";
            break;
        case 6:
        case 7:
        case 8:
            std::cout << "Summer\n";
            break;
        case 9:
        case 10:
        case 11:
            std::cout << "Autumn\n";
            break;
        default:
            std::cout << "Invalid month\n";
    }

    return 0;
}
```

#### 4. Menu-driven program

```cpp
#include <iostream>

int main() {
    int choice;

    std::cout << "1. Say Hello\n";
    std::cout << "2. Say Goodbye\n";
    std::cout << "3. Exit\n";
    std::cout << "Choose an option: ";
    std::cin >> choice;

    switch (choice) {
        case 1:
            std::cout << "Hello there!\n";
            break;
        case 2:
            std::cout << "Goodbye!\n";
            break;
        case 3:
            std::cout << "Exiting...\n";
            break;
        default:
            std::cout << "Not a valid option\n";
    }

    return 0;
}
```

***

### `switch` vs `else if` — when to use which

| Use `switch` when...                                             | Use `else if` when...                                   |
| ---------------------------------------------------------------- | ------------------------------------------------------- |
| Comparing **one variable** against several fixed values          | Checking **ranges** (`age >= 18`) or complex conditions |
| Working with `int`, `char`, `enum`                               | Working with `std::string`, `bool` logic, or `&&` / \`  |
| You want cleaner, more readable branching for many fixed options | You have relatively few, more complex conditions        |

***

### Quick Recap

* `switch (variable) { case value: ... break; default: ... }`
* **Always add `break;`** — otherwise execution "falls through" into the next case.
* `default:` is the fallback, like a final `else`.
* `switch` only works with integral types (`int`, `char`, `enum`) — **not** `std::string`.
* Intentional fall-through (stacking cases with no `break`) is a valid technique for grouping cases that share behavior.


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://alham-rizvi.gitbook.io/alhamrizvi/c++-notes/12.-switch-statements.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
