• Home
  • 4.5 switch Statement

4.5 switch Statement

View Categories

4.5 switch Statement

1 min read

Table of Contents

The switch statement provides a multi-way selection mechanism based on the value of an expression. It compares the expression against a sequence of case labels and executes the statements associated with the matching label.

The break statement is commonly used to terminate a case and prevent execution from continuing into the following cases. A default label can be used to handle values that do not match any of the specified cases.

Source Code #

#include <iostream>

int main()
{
    int day = 3;

    switch (day)
    {
        case 1:
            std::cout << "Monday\n";
            break;

        case 2:
            std::cout << "Tuesday\n";
            break;

        case 3:
            std::cout << "Wednesday\n";
            break;

        case 4:
            std::cout << "Thursday\n";
            break;

        default:
            std::cout << "Invalid day\n";
            break;
    }

    return 0;
}

Output #

Wednesday

Explanation #

  • The switch statement evaluates the expression day.
  • Each case label specifies a possible value that can match the switch expression.
  • When the value of day matches case 3, the statements associated with that case are executed.
  • The break statement terminates the switch statement and transfers execution to the statement following it.
  • Without break, execution can continue into subsequent case labels. This behavior is known as fallthrough.
  • The default label is executed when none of the case labels match the value of the switch expression.
  • A switch statement is useful when selecting between multiple discrete constant values.
  • return 0; terminates the program successfully.

Powered by BetterDocs

Leave a Reply

Your email address will not be published. Required fields are marked *