Switch is C++'s multiway decision statement.
It works like this: the value of an expression is successively tested against a list of integer or character constants. When a match is found, the statement sequence associated with that match is executed. The general form of the switch statement is
**************************************
switch(expression){
case constant1:
statement sequence
break;
case constant2:
statement sequence
break;
case constant3:
statement sequence
break;
.
.
.
.
default:
statement sequence
}
**************************************
The switch expression must evaluate to either a character or an integer value. In other words, floating-point expressions are not allowed. Frequently, the expression controlling the switch is simply a variable.
break stops the execution of code within a switch.
There are four important things to know about the switch statement.
1. The switch differs from the if in that switch can test only for equality, whereas the if conditional expression can be of any type.
2. No two case constants in the same switch can have identical values. Of course, a switch statement enclosed by an outer switch may have case constants in common.
3. A switch statement is usually more efficient than nested ifs.
4. The statement sequences associated with each case are nor blocks. However, the entire switch statement does define a block. The importance of this will become apparent as you learn more about C++.
Standard C++ specifies that a switch can have at least 16834 case statements.
You can have empty cases.
本文详细介绍了 C++ 中的 switch 语句,包括其语法结构、工作原理及注意事项。switch 语句用于实现多分支选择结构,通过比较表达式的值与一系列常量表达式的值来决定执行哪部分代码。文中还强调了 switch 语句中 case 常量的唯一性、break 语句的作用以及 switch 语句与 if 语句的区别。
1946

被折叠的 条评论
为什么被折叠?



