×

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

User-defined literals in C++

Introduction to User-Defined Literals: User-defined literals, introduced in C++11, are a way to extend the C++ language to allow users to define their literal suffixes and the corresponding behavior. These suffixes...

7 minutes read.

Structure of C++ Program

Many people believe that C++, an object-oriented programming (OOP) language, is the finest language for developing demanding applications. A superset of the C language is C++. Java, a closely comparable...

4 minutes read.

Differences between Local and Global Variable

Define Global Variable Global variables are those that may be accessible worldwide across a programme and are defined outside of any functions or blocks. It may be accessed by any function in...

3 minutes read.

C++ add two numbers using the function

Here we will learn how to add two numbers by creating function in C++. Let’s learn this with help of example. Code: - #include <iostream> using namespace std; int add_two_no(int a, int b); int main(){   int...

1 minute read.

C++ Data Abstraction

Object-oriented programming (OOP) provides a number of characteristics that enable programmers to design programmes based on a variety of ideas, reducing errors and increasing program flexibility. The abstraction of data...

7 minutes read.

Passing a Vector to a function in C++

A pointer is sent to the function when we feed it an array. However, there are two ways to pass a vector: Pass by Value Pass by Reference A copy of a vector...

3 minutes read.

Converting string into integer in C++

When programming in C++, we'll frequently need to change one data type to another. When we use C++ to create apps, we must transform data from one type to another. When...

7 minutes read.

C++ Exception Handling

Exception is an unexpected problem that occurs at program run time. This problem might include condition such as division by zero, running out of memory space, array out of bonds, etc....

2 minutes read.

C ++ Program: Alphabet Triangle and Number Triangle

Alphabet Triangle and Number Triangle An alphabet triangle is a triangle that typically looks like a pyramid or other triangles like an isosceles triangle, a right-angled triangle consisting of similar or...

4 minutes read.

C++ | C Plus Plus Data type

Data type in every language is very important. Data type means the different kinds of data that are supported by a particular programming language. A computer language’s data types specify the...

15 minutes read.

Classes and Objects in C++

When it comes to object-oriented programming, objects are the basic building blocks. Memory is taken up by objects, which contain data and methods or functions that operate on it. On...

3 minutes read.

Bitwise Operator vs Logical Operator

Bitwise Operator  Bitwise operators perform operations bit by bit on bits.The value is converted to abinary during operations like addition, subtraction, division, and so on. These operations are carried out at the...

3 minutes read.

Top best IDEs for C/C++ Developers in 2024

Nothing in the current digital world is conceivable without programming. Everything needs programming, from the cell phones in our pockets to self-driving cars. Programming is also necessary for the mouse...

9 minutes read.

Add two numbers represented by two arrays in C++

The array stores a number in such a way that each digit of the number is represented by an array element. As an example, The array number 147 is 1,4,7. To add...

3 minutes read.

C++ Features

C++ is a general-purpose programming language that evolved from the C language to include an object-oriented paradigm. It is a compiled and imperative language. Object-Oriented Programming Object-oriented programming language concepts: ClassObjectsEncapsulationPolymorphismInheritanceAbstraction Class: A Class...

4 minutes read.

fread() Function in C++ Programming

C++ language is used to make high-performance applications that can work efficiently, and it is one of the world's most popular languages. It is an object-oriented and high-level programming language;...

3 minutes read.

How the value is passed in C++

Introduction: The call-by-value method of giving arguments to a function duplicates the real value of an argument into the formal parameter of the function. In this instance, modifications to the parameter...

5 minutes read.

Observer Design Pattern in C++

The Observer design pattern is a behavioural design pattern that allows an object (known as the subject) to notify other objects (known as observers) when its state changes. This is...

3 minutes read.

How to create a button in C++

A button is an option through which a user can control to click a provided input to an application. There are several buttons, each with different styles, to maintain the...

3 minutes read.

Multiset in C++

Introduction Multisets are part of the C++ STL, or Standard Template Library. In C++, a multiset is a set of associative containers that hold ordered items. Items in a multiset can...

10 minutes read.