Switch-Case in C++

Switch-case statements are control flow structures in C++ that allow you to execute different blocks of code based on the value of a variable or an expression. It provides a convenient way to handle multiple possible outcomes without using a series of if-else statements. The syntax for a switch-case statement in C++ is as follows:

switch (expression)
{
    case value1:
        // code to be executed if expression is equal to value1
        break;
    case value2:
        // code to be executed if expression is equal to value2
        break;
    // add more cases as needed
    default:
        // code to be executed if expression doesn't match any case
        break;
}

Here's a breakdown of the different parts of the switch-case syntax:

  • The switch keyword indicates the start of the switch statement.
  • expression is the variable or expression whose value will be evaluated.
  • Each case represents a possible value that the expression can have.
  • The code block following each case statement will be executed if the value of expression matches the corresponding value.
  • The break statement is used to exit the switch block after executing a case. Without a break statement, execution will continue to the next case, leading to multiple cases being executed.
  • The default case is optional and is used to handle a situation where none of the previous cases match the value of the expression.

Now, let's take a look at an example to understand the usage of switch-case statements:

#include<iostream>
using namespace std;
int main() {
    int day;
    cout << "Enter a number (1-7): ";
    cin >> day;
    switch (day) {
        case 1:
            cout << "Sunday" << endl;
            break;
        case 2:
            cout << "Monday" << endl;
            break;
        case 3:
            cout << "Tuesday" << endl;
            break;
        case 4:
            cout << "Wednesday" << endl;
            break;
        case 5:
            cout << "Thursday" << endl;
            break;
        case 6:
            cout << "Friday" << endl;
            break;
        case 7:
            cout << "Saturday" << endl;
            break;
        default:
            cout << "Invalid input!" << endl;
            break;
    }
    return 0;
}