Coming Soon

This lesson is currently being developed

Switch statement basics

Master multi-way branching with switch statements.

Control Flow
Chapter
Beginner
Difficulty
45min
Estimated Time

What to Expect

Comprehensive explanations with practical examples

Interactive coding exercises to practice concepts

Knowledge quiz to test your understanding

Step-by-step guidance for beginners

Development Status

In Progress

Content is being carefully crafted to provide the best learning experience

Preview

Early Preview Content

This content is still being developed and may change before publication.

8.5 — Switch statement basics

In this lesson, you'll learn how to use switch statements to handle multiple-choice decisions efficiently, understand when switch is preferable to if-else chains, and master the fundamentals of multi-way branching.

What is a switch statement?

A switch statement provides an efficient way to execute different code based on the value of a variable. It's particularly useful when you need to compare a variable against many possible values.

switch (variable)
{
    case value1:
        // Code to execute if variable == value1
        break;
    case value2:
        // Code to execute if variable == value2
        break;
    default:
        // Code to execute if no case matches
        break;
}

Basic switch example

#include <iostream>

int main()
{
    int day = 3;
    
    switch (day)
    {
        case 1:
            std::cout << "Monday\n";
            break;
        case 2:
            std::cout << "Tuesday\n";
            break;
        case 3:
            std::cout << "Wednesday\n";
            break;
        case 4:
            std::cout << "Thursday\n";
            break;
        case 5:
            std::cout << "Friday\n";
            break;
        default:
            std::cout << "Weekend or invalid day\n";
            break;
    }
    
    return 0;
}

Output:

Wednesday

The importance of break statements

The break statement exits the switch block. Without it, execution continues to the next case (called "fall-through"):

Without break (fall-through)

#include <iostream>

int main()
{
    int score = 2;
    
    switch (score)
    {
        case 1:
            std::cout << "You scored 1\n";
        case 2:
            std::cout << "You scored 2\n";
        case 3:
            std::cout << "You scored 3\n";
        default:
            std::cout << "End of scoring\n";
    }
    
    return 0;
}

Output:

You scored 2
You scored 3
End of scoring

Notice how execution continued through all the following cases!

With break (normal behavior)

#include <iostream>

int main()
{
    int score = 2;
    
    switch (score)
    {
        case 1:
            std::cout << "You scored 1\n";
            break;
        case 2:
            std::cout << "You scored 2\n";
            break;
        case 3:
            std::cout << "You scored 3\n";
            break;
        default:
            std::cout << "Invalid score\n";
            break;
    }
    
    return 0;
}

Output:

You scored 2

Switch vs if-else chains

Using if-else chain

#include <iostream>

int main()
{
    char grade = 'B';
    
    if (grade == 'A')
    {
        std::cout << "Excellent!\n";
    }
    else if (grade == 'B')
    {
        std::cout << "Good job!\n";
    }
    else if (grade == 'C')
    {
        std::cout << "Average.\n";
    }
    else if (grade == 'D')
    {
        std::cout << "Below average.\n";
    }
    else if (grade == 'F')
    {
        std::cout << "Failed.\n";
    }
    else
    {
        std::cout << "Invalid grade.\n";
    }
    
    return 0;
}

Using switch (cleaner)

#include <iostream>

int main()
{
    char grade = 'B';
    
    switch (grade)
    {
        case 'A':
            std::cout << "Excellent!\n";
            break;
        case 'B':
            std::cout << "Good job!\n";
            break;
        case 'C':
            std::cout << "Average.\n";
            break;
        case 'D':
            std::cout << "Below average.\n";
            break;
        case 'F':
            std::cout << "Failed.\n";
            break;
        default:
            std::cout << "Invalid grade.\n";
            break;
    }
    
    return 0;
}

Output:

Good job!

Both produce the same result, but the switch is more readable when dealing with many cases.

What types can be used with switch?

Switch statements work with integral types and enumerations:

Valid types:

  • int
  • char
  • short
  • long
  • bool
  • enum types
  • Any integral type

Example with different types

#include <iostream>

int main()
{
    // Switch with char
    char operation = '+';
    switch (operation)
    {
        case '+':
            std::cout << "Addition\n";
            break;
        case '-':
            std::cout << "Subtraction\n";
            break;
        case '*':
            std::cout << "Multiplication\n";
            break;
        case '/':
            std::cout << "Division\n";
            break;
        default:
            std::cout << "Unknown operation\n";
            break;
    }
    
    // Switch with bool (though rarely used)
    bool isActive = true;
    switch (isActive)
    {
        case true:
            std::cout << "Status: Active\n";
            break;
        case false:
            std::cout << "Status: Inactive\n";
            break;
    }
    
    return 0;
}

Output:

Addition
Status: Active

Invalid types (won't compile):

// These don't work with switch:
std::string text = "hello";
double number = 3.14;
float value = 2.5f;

// switch (text) { ... }    // Error!
// switch (number) { ... }  // Error!
// switch (value) { ... }   // Error!

The default case

The default case is optional but recommended. It executes when no other case matches:

#include <iostream>

int main()
{
    int choice = 99;
    
    switch (choice)
    {
        case 1:
            std::cout << "Option 1 selected\n";
            break;
        case 2:
            std::cout << "Option 2 selected\n";
            break;
        case 3:
            std::cout << "Option 3 selected\n";
            break;
        default:
            std::cout << "Invalid choice: " << choice << "\n";
            break;
    }
    
    return 0;
}

Output:

Invalid choice: 99

The default case can appear anywhere in the switch, but conventionally goes at the end.

Practical examples

Example 1: Simple calculator

#include <iostream>

int main()
{
    double num1, num2;
    char operation;
    
    std::cout << "Enter first number: ";
    std::cin >> num1;
    
    std::cout << "Enter operation (+, -, *, /): ";
    std::cin >> operation;
    
    std::cout << "Enter second number: ";
    std::cin >> num2;
    
    switch (operation)
    {
        case '+':
            std::cout << num1 << " + " << num2 << " = " << (num1 + num2) << std::endl;
            break;
            
        case '-':
            std::cout << num1 << " - " << num2 << " = " << (num1 - num2) << std::endl;
            break;
            
        case '*':
            std::cout << num1 << " * " << num2 << " = " << (num1 * num2) << std::endl;
            break;
            
        case '/':
            if (num2 != 0)
            {
                std::cout << num1 << " / " << num2 << " = " << (num1 / num2) << std::endl;
            }
            else
            {
                std::cout << "Error: Division by zero!\n";
            }
            break;
            
        default:
            std::cout << "Error: Invalid operation '" << operation << "'\n";
            break;
    }
    
    return 0;
}

Sample Output:

Enter first number: 15
Enter operation (+, -, *, /): *
Enter second number: 4
15 * 4 = 60

Example 2: Menu system

#include <iostream>

int main()
{
    int choice;
    
    std::cout << "=== MAIN MENU ===\n";
    std::cout << "1. New Game\n";
    std::cout << "2. Load Game\n";
    std::cout << "3. Settings\n";
    std::cout << "4. Help\n";
    std::cout << "5. Exit\n";
    std::cout << "Enter your choice (1-5): ";
    
    std::cin >> choice;
    
    switch (choice)
    {
        case 1:
            std::cout << "\nStarting new game...\n";
            std::cout << "Welcome to Adventure Quest!\n";
            break;
            
        case 2:
            std::cout << "\nLoading saved game...\n";
            std::cout << "Game loaded successfully!\n";
            break;
            
        case 3:
            std::cout << "\nOpening settings menu...\n";
            std::cout << "Configure your preferences here.\n";
            break;
            
        case 4:
            std::cout << "\n=== HELP ===\n";
            std::cout << "Use WASD keys to move.\n";
            std::cout << "Press SPACE to interact.\n";
            break;
            
        case 5:
            std::cout << "\nThank you for playing!\n";
            std::cout << "Goodbye!\n";
            break;
            
        default:
            std::cout << "\nInvalid choice! Please select 1-5.\n";
            break;
    }
    
    return 0;
}

Sample Output:

=== MAIN MENU ===
1. New Game
2. Load Game
3. Settings
4. Help
5. Exit
Enter your choice (1-5): 1

Starting new game...
Welcome to Adventure Quest!

Example 3: Month days calculator

#include <iostream>

int main()
{
    int month;
    
    std::cout << "Enter month number (1-12): ";
    std::cin >> month;
    
    switch (month)
    {
        case 1:   // January
        case 3:   // March
        case 5:   // May
        case 7:   // July
        case 8:   // August
        case 10:  // October
        case 12:  // December
            std::cout << "This month has 31 days.\n";
            break;
            
        case 4:   // April
        case 6:   // June
        case 9:   // September
        case 11:  // November
            std::cout << "This month has 30 days.\n";
            break;
            
        case 2:   // February
            std::cout << "This month has 28 days (29 in leap years).\n";
            break;
            
        default:
            std::cout << "Invalid month number! Please enter 1-12.\n";
            break;
    }
    
    return 0;
}

Sample Output:

Enter month number (1-12): 4
This month has 30 days.

Notice how multiple cases can share the same code by omitting break statements between them.

Multiple statements in case blocks

You can have multiple statements in each case. Use braces for clarity with complex blocks:

#include <iostream>

int main()
{
    int accessLevel = 2;
    
    switch (accessLevel)
    {
        case 1:
        {
            std::cout << "Guest Access\n";
            std::cout << "Limited features available\n";
            bool canRead = true;
            bool canWrite = false;
            std::cout << "Read: " << canRead << ", Write: " << canWrite << std::endl;
            break;
        }
        
        case 2:
        {
            std::cout << "User Access\n";
            std::cout << "Standard features available\n";
            bool canRead = true;
            bool canWrite = true;
            std::cout << "Read: " << canRead << ", Write: " << canWrite << std::endl;
            break;
        }
        
        case 3:
        {
            std::cout << "Admin Access\n";
            std::cout << "All features available\n";
            bool canRead = true;
            bool canWrite = true;
            bool canDelete = true;
            std::cout << "Read: " << canRead << ", Write: " << canWrite;
            std::cout << ", Delete: " << canDelete << std::endl;
            break;
        }
        
        default:
        {
            std::cout << "Invalid access level\n";
            break;
        }
    }
    
    return 0;
}

Output:

User Access
Standard features available
Read: 1, Write: 1

Using switch with enums

Switch statements work particularly well with enumerations:

#include <iostream>

enum class Color
{
    Red,
    Green,
    Blue,
    Yellow,
    Purple
};

int main()
{
    Color favoriteColor = Color::Blue;
    
    switch (favoriteColor)
    {
        case Color::Red:
            std::cout << "Red is the color of fire and passion!\n";
            break;
            
        case Color::Green:
            std::cout << "Green is the color of nature and growth!\n";
            break;
            
        case Color::Blue:
            std::cout << "Blue is the color of sky and ocean!\n";
            break;
            
        case Color::Yellow:
            std::cout << "Yellow is the color of sunshine and happiness!\n";
            break;
            
        case Color::Purple:
            std::cout << "Purple is the color of royalty and mystery!\n";
            break;
    }
    
    return 0;
}

Output:

Blue is the color of sky and ocean!

When to use switch vs if-else

Use switch when:

  • Comparing one variable against multiple specific values
  • Values are known at compile time
  • Working with integral types or enums
  • You have many cases (usually 3+ cases)
  • Code readability is important

Use if-else when:

  • Comparing different variables
  • Using complex conditions (ranges, logical operators)
  • Working with floating-point numbers or strings
  • Conditions involve function calls or complex expressions
  • You have only 1-2 conditions

Example: When if-else is better

#include <iostream>

int main()
{
    int age = 25;
    double salary = 50000.0;
    bool hasExperience = true;
    
    // This is better with if-else (complex conditions)
    if (age >= 25 && salary > 40000)
    {
        std::cout << "Eligible for premium membership\n";
    }
    else if (age >= 18 && hasExperience)
    {
        std::cout << "Eligible for standard membership\n";
    }
    else
    {
        std::cout << "Eligible for basic membership\n";
    }
    
    return 0;
}

Best practices

1. Always include default case

switch (value)
{
    case 1:
        // Handle case 1
        break;
    case 2:
        // Handle case 2
        break;
    default:
        // Handle unexpected values
        break;
}

2. Always include break statements

// Good - clear intent
switch (choice)
{
    case 1:
        doOption1();
        break;  // Explicit break
    case 2:
        doOption2();
        break;  // Explicit break
}

3. Use braces for complex cases

switch (type)
{
    case 1:
    {
        int localVar = calculateSomething();
        processData(localVar);
        break;
    }
    case 2:
    {
        int anotherVar = calculateSomethingElse();
        processOtherData(anotherVar);
        break;
    }
}

4. Keep cases simple

// Good - simple cases
switch (command)
{
    case 'q':
        quit();
        break;
    case 's':
        save();
        break;
    case 'l':
        load();
        break;
}

// Less ideal - complex logic in cases
switch (command)
{
    case 'q':
        // Lots of complex code here...
        break;
}

Common mistakes

1. Forgetting break statements

// BUG: Missing breaks cause fall-through
switch (grade)
{
    case 'A':
        std::cout << "Excellent\n";  // Falls through to next case!
    case 'B':
        std::cout << "Good\n";       // This will also print for 'A'
        break;
}

2. Using non-integral types

std::string text = "hello";
// switch (text) { ... }  // Error! strings not allowed

3. Variable declarations without braces

switch (value)
{
    case 1:
        int x = 10;  // Error! Variable declaration needs braces
        break;
    case 2:
    {
        int y = 20;  // OK - in a block
        break;
    }
}

Summary

Switch statements provide efficient multi-way branching:

  • Purpose: Compare one variable against multiple specific values
  • Syntax: Uses case labels and break statements
  • Types: Works with integral types and enums
  • Default: Optional catch-all case for unmatched values
  • Fall-through: Execution continues without break
  • Performance: Often more efficient than if-else chains

Key advantages:

  • Clean, readable syntax for multiple cases
  • Compiler optimizations possible
  • Clear intent for multi-way branching
  • Works well with enumerations

Switch statements are particularly useful for menus, state machines, and any situation where you need to handle multiple discrete values efficiently.

Quiz

  1. What types of variables can be used in switch statements?
  2. What happens if you forget to include a break statement in a case?
  3. When should you use switch instead of if-else?
  4. Is the default case required in a switch statement?
  5. Can you have multiple statements in a single case without braces?

Practice exercises

  1. Grade calculator: Create a switch statement that converts letter grades (A, B, C, D, F) to their point values (4.0, 3.0, 2.0, 1.0, 0.0).

  2. Vending machine: Write a vending machine simulator that shows different snacks and prices based on button selections (1-9), with appropriate error handling.

  3. Roman numeral converter: Create a program that converts single digits (1-9) to Roman numerals using a switch statement.

  4. Text adventure: Design a simple text-based adventure game that uses switch statements to handle different room choices and actions.

Continue Learning

Explore other available lessons while this one is being prepared.

View Course

Explore More Courses

Discover other available courses while this lesson is being prepared.

Browse Courses

Lesson Discussion

Share your thoughts and questions

💬

No comments yet. Be the first to share your thoughts!

Sign in to join the discussion