The switch statement in C++ is used to evaluate an expression and compare it with multiple cases, and execute the block of code associated with the first matching case. The switch statement can be used as an alternative to if-else statements when there are multiple options to choose from.
The basic syntax of the switch statement is as follows:
switch(expression) { case constant-expression: // code to execute if expression matches the constant-expression break; case constant-expression: // code to execute if expression matches the constant-expression break; // more cases can be added here default: // code to execute if none of the above cases match the expression }
Here’s an explanation of the different components of the switch statement:
expression
: This is the value that will be evaluated in the switch statement.case constant-expression
: This is a specific value that the expression will be compared to. If the expression matches the constant-expression, the code block associated with that case will be executed.break
: This is used to exit the switch statement after a case is executed. Without a break statement, the switch statement will continue to execute the code blocks of all cases following the matching case until a break statement is encountered.default
: This is the code block that will be executed if none of the cases match the expression.
Let’s look at an example of a switch statement in action:
#include <iostream> using namespace std; int main() { int day = 5; switch (day) { case 1: cout << "Monday" << endl; break; case 2: cout << "Tuesday" << endl; break; case 3: cout << "Wednesday" << endl; break; case 4: cout << "Thursday" << endl; break; case 5: cout << "Friday" << endl; break; default: cout << "Invalid day" << endl; break; } return 0; }
In this example, the switch statement evaluates the value of the day
variable and compares it to each case. Since the value of day
is 5, the code block associated with case 5 is executed, which outputs “Friday” to the console.
If the value of day
was not one of the specified cases (1 through 5), the default code block would have been executed instead.
I hope this helps you understand how to use the switch statement in C++!