switch case
时间: 2023-10-16 11:30:17 浏览: 98
js中switch case循环实例代码
5星 · 资源好评率100%
Switch case is a programming construct used in many programming languages, including C++, Java, and Python, that allows a program to execute different blocks of code depending on the value of a variable or an expression.
The switch statement evaluates an expression or variable and compares it with a series of case values. If the expression matches a case value, the corresponding block of code is executed. If the expression does not match any of the case values, the default block of code is executed.
Here is an example of a switch case statement in C++:
```
int day = 2;
switch (day) {
case 1:
cout << "Monday" << endl;
break;
case 2:
cout << "Tuesday" << endl;
break;
case 3:
cout << "Wednesday" << endl;
break;
default:
cout << "Invalid day" << endl;
break;
}
```
In this example, the switch statement evaluates the value of the variable `day`. If `day` is equal to 1, the program executes the code in the first case block, which outputs "Monday". If `day` is equal to 2, the program executes the code in the second case block, which outputs "Tuesday". If `day` is equal to 3, the program executes the code in the third case block, which outputs "Wednesday". If `day` does not match any of the case values, the program executes the default block, which outputs "Invalid day". The `break` statement at the end of each case block is used to exit the switch statement and prevent the program from executing the code in the other case blocks.
阅读全文