Why Breaks are used in C++ Switch Statement?

In C++, the switch statement allows us to select a code block to be executed based on some conditions among many alternatives (listed in the form of cases). The break keyword plays an important role in the functioning of a switch statement. In this article, we will learn why breaks are used in C++ switch statements.

Need of Break in C++ Switch Statement

In a switch statement, the break keyword is used as a control mechanism to stop the execution of code blocks once the required condition is met and the case is executed.

When a case is matched in switch statement, not only the code of that case is executed, but all the code of the cases below that case is executed. To prevent this, break is used.

Each case block finishes with the break statement. Without it, the program will continue to execute all the subsequent cases until the end of the switch statement is reached this condition is called fallthrough behavior.

Syntax of break in C++ Switch Statement

switch(expr)
{
case value1:
// code to be executed if expr = valuet1;
break;
//....more case
default:
// code to be executed if expression doesn't match any constants;
}

C++ Program to Demonstrate the Use of Break in Switch Statement

The below example demonstrates how we can use the break keyword in a switch statement in C++.

C++
// C++ program to demonstrate the use of break in switch
// statement
#include <iostream>
using namespace std;

int main()
{

    // Declare and initialize a char variable as case value
    char grade = 'B';

    // Switch statement
    switch (grade) {
    // different cases of the switch statement
    case 'A':
        cout << "Excellent!" << endl;
        break;
    case 'B':
        cout << "Good job!" << endl;
        break; // will return from here
    case 'C':
        cout << "You can do better." << endl;
        break;
    default:
        cout << "Invalid grade." << endl;
    }

    return 0;
}

Output
Good job!

Time Complexity: O(1) 
Auxiliary Space: O(1)

Note: Using the break statement in switch case is optional, if omitted, execution will continue on into the next case but it is recommended to use break as it gives us more control over the flow of our program and prevents unintentional fall-through between cases.