C++ Case Statement: Usage Guide & Examples
In C++, the case statement is used to match different conditional values in a switch statement. The switch statement will select which case statement block to execute based on the value of the expression. For example:
switch (expression) {
case value1:
// 当表达式的值等于value1时执行这里的代码
break;
case value2:
// 当表达式的值等于value2时执行这里的代码
break;
default:
// 默认情况下执行这里的代码
}
In the code above, if the value of the expression is equal to value1, the code in the first case statement block will be executed; if the value of the expression is equal to value2, the code in the second case statement block will be executed; if the value of the expression does not equal any of the values in the case statements, the code in the default statement block will be executed.
It is important to note that each case block must end with a break statement; otherwise, the program will continue to execute the next case block until it encounters a break statement.