×

C++ Switch

In C++, an expression or variable can be tested against a range of constant values using a switch statement, which is a control flow statement. It offers a productive method for performing many code blocks according to the matched case value. By enabling the direct selection of execution pathways, switches improve readability and speed in contrast to if-else expressions, which analyze circumstances in a sequential manner.

The switch statement only works with integral types (int, char, and enum) and requires that case labels have constant values. The break statement prevents fall-through behavior and only allows the matching case to execute. If no case matches, an optional default case can be used as a fallback.

Syntax:

It has the following syntax:

switch (expression) {

    case value1:

        // Code to execute if expression == value1

        break;

    case value2:

        // Code to execute if expression == value2

        break;

    ...

    default:

        // Code to execute if no case matches

}

Working of switch statement:

  • The evaluation is done on the expression inside the switch statement.
  • The value of the expression is compared to each case label.
  • If a match is found, the corresponding code block is executed.
  • The break statement ensures that the execution exits the switch block following the execution of a matching case.
  • If no case matches, the default block (if provided) executes.

Key Features:

Several key features of switch statement in C++ are as follows:

  1. Compatibility is limited to integral or character types (int, char, and enum).
  2. Instead of variables, the cases must be literals or constant expressions.
  3. The break statement prevents the execution of subsequent cases, or fall-through.
  4. If the break is not used, the execution proceeds to the next scenario (fall-through behavior).

Algorithm:

Start

Evaluate the expression inside the switch statement.

Compare the result of the expression with each case label.

If a match is found:
  • Execute the corresponding block of code.
  • If a break statement is present, exit the switch block.
If no match is found:
  • Execute the default block (if provided).
Continue with the rest of the program.

End

Pseudo code:

BEGIN

    Read expression_value

    SWITCH (expression_value)

        CASE value1:

            Execute code block 1

            Break

        CASE value2:

            Execute code block 2

            Break

        CASE value3:

            Execute code block 3

            Break

        ...

        DEFAULT:

            Execute default code block

    END SWITCH

END

Example 1:

Let us take an example to illustrate the switch statement in C++:

#include <iostream>

using namespace std;

int main() {

    int day = 3;


    switch (day) {

        case 1:

            cout << "Monday";

            break;

        case 2:

            cout << "Tuesday";

            break;

        case 3:

            cout << "Wednesday";

            break;

        case 4:

            cout << "Thursday";

            break;

        case 5:

            cout << "Friday";

            break;

        default:

            cout << "Weekend!";

    }

    return 0;

}

Output:

Wednesday

Example 2:

Let us take another example to illustrate the switch statement in C++.

#include <iostream>

using namespace std;

int main() {

    char grade = 'B';

    switch (grade) {

        case 'A':

            cout << "Excellent! ";

        case 'B':

            cout << "Good job!";

            break;

        case 'C':

            cout << "You passed.";

            break;

        default:

            cout << "Invalid grade.";

    }

    return 0;

}

Output:

Excellent! Good job!

Example 3:

Let us take another example to illustrate the switch statement in C++.

#include <iostream>

using namespace std;

int main() {

    char operation;

    double num1, num2;

    // Taking input from the user

    cout << "Enter an operator (+, -, *, /): ";

    cin >> operation;

    cout << "Enter two numbers: ";

    cin >> num1 >> num2;


    // Switch statement to perform the operation

    switch (operation) {

        case '+':

            cout << "Result: " << (num1 + num2);

            break;

        case '-':

            cout << "Result: " << (num1 - num2);

            break;

        case '*':

            cout << "Result: " << (num1 * num2);

            break;

        case '/':

            // Checking for division by zero

            if (num2 != 0)

                cout << "Result: " << (num1 / num2);

            else

                cout << "Error! Division by zero is not allowed.";

            break;

        default:

            cout << "Invalid operator!";

    }

    return 0;

}

Output:

Enter an operator (+, -, *, /): +

Enter two numbers: 5 6

Result: 11

Advantages of using Switch over If-Else:

Several advantages of switch case over if-else in C++ are as follows:

  • Improved Readability: When handling several circumstances, it is easier to comprehend.
  • Effective Execution: Compilers may optimize switches more effectively than several if-else statements.
  • Simpler Maintenance: It is easy to add and remove cases.

Limitations:

Several limitations of switch case in C++ are as follows:

  • Exclusively Supports Certain Data Types: Switch supports int, char, and enum but not float, double, or string (save for C++17’s std::string_view).
  • Case Values Must Be Fixed: Case labels cannot contain variables or expressions.
  • Limited Flexibility: Unlike if-else, switches cannot handle complex situations.

Conclusion:

In C++, the switch statement is a powerful control structure that simplifies multi-way decision-making by comparing a single expression to multiple fixed values. It improves code readability and speed when compared to multiple if-else statements, especially when handling a large number of discrete instances. Break prevents accidental fall-through by ensuring that only the matching case executes. Although Switch has some limitations, such as only supporting integral types (char, enum, and int) and requiring case labels to be constant expressions, Switch is still a helpful tool for structuring clear and efficient decision-making logic in C++ applications.


Related Topics

strcat() vs strncat() in C++

In this tutorial, we will explore about strcat() and strncat() in the most usable language C++. We will also look at the difference between them. strcat() C++ is a computer language with...

4 minutes read.

Reverse a String using Stack C/C++

Reverse the given string using stack. To turn "tutorialandexample" into "elpmaxednalairotut," for instance. Here is a straightforward stack-based technique for reversing strings. Algorithm: 1) Make a stack that is empty. 2) Push each character...

3 minutes read.

C++ Namespaces

An Overview In each scope, a name can only represent one entity. As a result, there cannot be two independent variables with the similar names in the same scope, as this may cause...

10 minutes read.

The Stock Span Problem

It is necessary to determine the span of a stock's price throughout all n days in order to solve the stock span problem, which involves a set of n daily...

5 minutes read.

rand() and srand() in C / C++

In this tutorial, we'll explore the syntax, usage, and examples of the C++ STL functions rand() and srand(). What exactly is rand()? The C++ STL's built-in rand() function is defined in the...

3 minutes read.

Program to convert infix to postfix expression in C++

Parentheses are frequently employed in mathematical formulas to make their interpretation easier to understand. However, with computers, parenthesis in an expression might lengthen the time it takes to find a...

7 minutes read.

Reverse a Number in C++

In this tutorial, you'll learn how to utilize a C++ program to reverse a number entered by a user at runtime. Because there are various ways to write a C++...

3 minutes read.

C++ Deque

Definition: Deque or the Doubly ended queue is a data structure or operation performed under queue where insertion and deletion are allowed at both ends. A deque is an ordered collection of...

5 minutes read.

C++ Call by Reference

Call by Reference is a C++ method for passing arguments to a function that enables us to pass the actual memory address of the parameter rather than a copy of...

4 minutes read.

OOPs Concepts in C++

C++ Object-Oriented Programming Concepts C++ uses the concept of object-oriented programming. Object Oriented Programming has some prominent features: Object Class Data abstraction Encapsulation Polymorphism Inheritance Message passing Object An object is the basic unit...

2 minutes read.

Initialize Array of objects with parameterized constructors in C++

Initialize Array of objects with parameterized constructors in C++ When a class is defined, only the specification for the object is specified; no memory or capacity is allocated. You need to...

3 minutes read.

C++ 11 vs C++ 14 vs C++ 17

C++ is a language that is used to create a high-performance application. C++ 11, C++ 14, and C++ 17 are the different version of C++. There are some differences between...

1 minute read.

Compile Time Polymorphism in C++

What is Polymorphism? Polymorphism refers to the existence of various forms. Polymorphism can be simply defined as a message's capacity to be presented in multiple forms. One application of polymorphism in...

4 minutes read.

C++ String Class and its Applications

The String class is available in C++. The character array is represented by the C string. The string class in C++ has a few different attributes. It contains several functions...

4 minutes read.

Palindrome using For loop in C++

A palindrome is a word, number, phrase, or other sequence of letters that reads the same backward as forward, such as 101 or MOM. Like other programming languages, C++ also allows...

6 minutes read.

C++ String

A string is a collection of characters. C++ programming language supports both C string as well as standard C++ library string. In C++, string is an object of std::string class. C Style String The C style...

5 minutes read.

Floating Point Operations and Associativity in C, C++ and Java

In this tutorial, we are going to compare Floating-point operations and the concept of associativity. Before we apply the concept of associativity in the floating-point operations in all three programming...

3 minutes read.

Virtual Functions and Runtime Polymorphism in C++

In this tutorial, we will explore more on virtual functions and runtime polymorphism in the most useful language C++. A virtual function is a member function with the keyword virtual used...

6 minutes read.

Initialize Vector in C++

Initialize Vector in C++  The following comparison operators are defined for vector and those are given below. ==, <, <=, !=, >,>=  This allows you to access the element of a vector using...

3 minutes read.

getline() Function and Character Array in C++

In this article, we will explore about some concepts on getline() function and character array in the most useful language C++. The getline() method in C++ is simply a standard library...

6 minutes read.