D A R K - C O D E R

Loading

C++ Switch Statements | Understanding the Syntax and Usage of Switch in C++

C++ provides various control structures that enable the programmer to alter the flow of execution of a program. One such control structure is the switch statement. The switch statement is used to select one of many alternatives, based on the value of a control expression.

In this article, we will discuss the syntax and usage of switch statements in C++. We will also provide examples to demonstrate how to use switch statements in different situations.

What is a Switch Statement?

A switch statement is a control statement in C++ that allows a program to choose between a set of alternatives based on the value of a control expression. The control expression is evaluated once, and the program compares its value to each of the values in the case labels. If a match is found, the corresponding statement(s) are executed.

Syntax of Switch Statement

The syntax of a switch statement is as follows:

switch(expression){
    case constant1: 
        // statements to be executed if expression equals constant1
        break;
    case constant2: 
        // statements to be executed if expression equals constant2
        break;
    .
    .
    .
    default:
        // statements to be executed if none of the cases match
}

The switch keyword starts the switch statement and is followed by the control expression in parentheses. The body of the switch statement is enclosed in curly braces {}.

Each case label specifies a constant value that the control expression is compared against. If the value of the control expression matches a case label, the statements following that case label are executed until the break statement is encountered. The break statement causes the program to exit the switch statement and continue executing the code that follows it.

The default label is optional and specifies the code to be executed if none of the case labels match the value of the control expression.

Example 1:

Using Switch Statement to Check Day of the Week

Let’s look at an example of a switch statement that checks the day of the week based on a numeric value.

#include 
using namespace std;

int main() {
    int day = 3;

    switch(day) {
        case 1:
            cout