Mastering Switch in C++: An Easy Guide

Introduction

Imagine you’re playing a game where you have to make decisions at different points. Without the switch statement in C++, you would have to write a lot of if-else statements, making the code lengthy and confusing. The switch statement is like a shortcut that allows you to choose different paths based on different conditions.

It makes your code more concise, readable, and easier to maintain. In this article, we will explore the switch statement, its purpose, syntax, and real-life examples to understand how it can streamline decision-making in your programs. Let’s dive in!

What Exactly is a Switch in C++?

In C++, a switch is a control structure used to make decisions based on the value of an expression. It allows the program to execute specific code blocks based on different possible values of the expression. The switch expression is compared with different cases, and the corresponding code block is executed when a match is found. This provides a convenient way to handle multiple choices or options within the program’s logic flow.

Syntax:

C++
switch (expression) {
    case constant1:
        // Code to execute if expression equals constant1
        break;
    case constant2:
        // Code to execute if expression equals constant2
        break;
    // ... more cases ...
    default:
        // Code to execute if expression doesn't match any case
}

In this syntax:

  • expression‘ is the value you want to compare.
  • case constantX‘ represents a specific value that ‘expression‘ might have.
  • Inside each ‘case‘, you write the code you want to execute if ‘expression‘ matches the corresponding ‘constantX‘.
  • The ‘break‘ statement is used to exit the ‘switch‘ statement after a case is executed. If ‘break‘ is omitted, the program will continue executing the following case(s) as well.
  • The ‘default‘ case is optional and is executed if none of the case values match the ‘expression‘.
Mastering Switch In C++: An Easy Guide
Switch in C++

How Do I Use a Switch in C++?

Using a switch statement in C++ involves several key steps.

  • Setup:
    • Begin by defining a variable (usually of integer or character type) that you want to evaluate.
    • Declare the switch statement using the ‘switch‘ keyword.
  • Cases:
    • List different cases within the switch statement using the case keyword followed by a constant value.
    • For each case, add a colon : and write the code that should execute when the variable matches that case.
  • Code Blocks:
    • Code blocks for each case can include multiple statements. However, avoid falling through cases (not using ‘break‘) unintentionally.
  • Default Case:
    • Optionally, include a ‘default‘ case. This block will execute if none of the cases match the variable.
  • Break:
    • End each case with the ‘break‘ statement to exit the switch block.
  • Flow Control:
    • When the switch statement is encountered, the program checks the variable against each case.
    • Once a match is found, the corresponding code block executes, and the switch block exits (unless a break is missing).
  • Use Cases:
    • Switch statements are commonly used for menu selection, handling different options, or mapping values to actions.

Real-life Example of Switch in C++

Let’s talk about the ‘switch‘ statement in C++. A ‘switch‘ statement is a type of selection control mechanism used to allow the value of a variable or expression to change the control flow of the program execution.

Here’s a simple real-life analogy: Imagine going to an ice cream shop. The menu is your ‘switch‘ statement. You’ll make a choice (let’s ˝call it ‘flavour_choice‘), and the menu will give you the ice cream based on what you choose (each choice being a ‘case‘ in the switch statement).

Now let’s transform this scenario into a C++ code:

C++
#include<iostream>
using namespace std;

int main() {
    int flavour_choice;

    cout << "Ice Cream Menu:\n";
    cout << "1. Vanilla\n";
    cout << "2. Chocolate\n";
    cout << "3. Strawberry\n";
    cout << "4. Mint\n";
    cout << "Enter your choice: ";
    cin >> flavour_choice;

    switch (flavour_choice) {
        case 1:
            cout << "You've chosen Vanilla!";
            break;

        case 2:
            cout << "You've chosen Chocolate!";
            break;

        case 3:
            cout << "You've chosen Strawberry!";
            break;

        case 4:
            cout << "You've chosen Mint!";
            break;

        default:
            cout << "Invalid choice!";
    }

    return 0;
}

Output:

C++
Ice Cream Menu:
1. Vanilla
2. Chocolate
3. Strawberry
4. Mint
Enter your choice: 

Explanation:

  • User Input:
    • You input a number (1 to 4) to make a choice.
  • Switch Statement:
    • The entered number is checked using a switch statement.
  • Multiple Choices:
    • Depending on your input, it responds with a message for each choice (1 to 4).
  • Default Case:
    • If you input any other number, the default case triggers and displays “Invalid choice!”.
  • Break Statements:
    • The break statement is crucial to stop executing cases once a match is found. It prevents unintended execution.

A Problem to Solve

Problem: Write a program that represents a simple calculator capable of performing operations like addition, subtraction, multiplication, and division. The user should input two numbers and choose an operation. The calculator should perform the chosen operation on the provided numbers and print the result.

This is how the interaction should look:

  1. Encourage the user to enter the first number.
  2. Encourage the user to enter the second number.
  3. Show the operations menu:
    • 1 for Addition
    • 2 for Subtraction
    • 3 for Multiplication
    • 4 for Division
  4. Ask the user to choose an operation.
  5. Perform the selected operation and display the result.
  6. If the user chooses an invalid option, show an error message.

Hints:

  • You can use the ‘cin‘ object to take input from the user.
  • The ‘cout‘ object can help you display messages to the user.
  • You will need a ‘switch‘ statement to process the user’s choice of operation.
  • Make sure to handle the division by zero scenario properly.

Let’s Try Out Some Switch Examples

Example 1

C++
#include <iostream>
using namespace std;

int main() {
    int day;
    cout << "Enter a number between 1 and 7: ";
    cin >> day;

    switch(day) {
        case 1:
            cout << "Monday" << endl;
            break;
        case 2:
            cout << "Tuesday" << endl;
            break;
        case 3:
            cout << "Wednesday" << endl;
            break;
        case 4:
            cout << "Thursday" << endl;
            break;
        case 5:
            cout << "Friday" << endl;
            break;
        case 6:
            cout << "Saturday" << endl;
            break;
        case 7:
            cout << "Sunday" << endl;
            break;
        default:
            cout << "Invalid input!" << endl;
    }

    return 0;
}

Output:

C++
Enter a number between 1 and 7: 3
Wednesday

Explanation:

  • The code asks the user to input a number between 1 and 7.
  • Using the ‘switch‘ statement, it compares the input number to specific cases.
  • For each case from 1 to 7, it prints the corresponding day of the week.
  • If the input doesn’t match any case (not in the range 1-7), it shows “Invalid input!”
  • This program helps identify the day of the week based on the user’s input number.

Example 2

C++
#include <iostream>
using namespace std;

int main() {
    int choice;

    cout << "Choose an option:\n";
    cout << "1. Apple\n";
    cout << "2. Banana\n";
    cout << "3. Orange\n";
    cout << "4. Exit\n";

    cin >> choice;

    switch (choice) {
        case 1:
            cout << "You selected Apple.\n";
            break;
        case 2:
            cout << "You selected Banana.\n";
            break;
        case 3:
            cout << "You selected Orange.\n";
            break;
        case 4:
            cout << "Exiting...\n";
            break;
        default:
            cout << "Invalid choice.\n";
            break;
    }

    return 0;
}

Output:

C++
Choose an option:
1. Apple
2. Banana
3. Orange
4. Exit
2
You selected Banana.

Explanation:

  • The user was prompted to choose an option.
  • The ‘switch‘ statement evaluates the chosen value.
  • Depending on the value, a corresponding ‘case‘ block is executed.
  • Message related to the selected option is displayed.
  • The program concludes after executing the selected case or default case.

The Good and the Bad of Using a Switch in C++

ProsCons
Easy to read and understandLimited to comparing discrete values
Provides a structured approachCannot evaluate complex conditions
Can handle multiple casesRequires a break statement to avoid fallthrough
Efficient for a large number of casesNo support for range-based cases
Offers a default case for unmatched valuesDifficult to modify or add new cases
Pros and Cons

What Should I Remember?

  • The switch statement in C++ is a powerful tool for making decisions based on multiple possible values.
  • It provides a structured approach to handling different cases or options.
  • Each case represents a specific value or condition to be evaluated.
  • The break statement is used to exit the switch block after a case is executed to prevent fall-through to subsequent cases.
  • It is important to include a default case to handle unmatched values or conditions.
  • The switch statement can make code more readable and efficient when used appropriately.
  • Understanding how and when to use the switch statement can enhance your programming skills.

Conclusion

In conclusion, the ‘switch‘ statement in C++ is a powerful control structure that simplifies decision-making within programs. It provides an efficient way to handle multiple possible cases based on a single variable’s value. By using ‘switch‘, you can enhance the readability of your code and reduce the complexity of nested ‘if‘ and ‘else‘ statements. This construct proves especially useful when dealing with a series of mutually exclusive choices, allowing you to streamline your code and improve its maintainability.

FAQs

Q1.What is a switch statement in C++?

A switch statement is like a control room that lets you choose different actions based on different conditions.

Q2.Why was the switch statement introduced in C++?

The switch statement was introduced to make it easier and more efficient to handle multiple conditions, instead of using lots of if-else statements.

Q3.Can I use conditions in a switch statement in C++?

No, switch statements in C++ only allow exact values. You cannot use conditions.

Q4.What is a fall-through in a switch statement in C++?

A fall-through happens when a case in a switch statement is executed and the control falls through to the next case because there’s no break statement.

Q5.What types can be used with a switch statement in C++?

Switch statements in C++ can only be used with whole numbers or enumeration types.

Avatar Of Deepak Vishwakarma
Deepak Vishwakarma

Founder

RELATED Articles

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.