C++_Switch Statement

本文详细介绍了 C++ 中的 switch 语句,包括其语法结构、工作原理及注意事项。switch 语句用于实现多分支选择结构,通过比较表达式的值与一系列常量表达式的值来决定执行哪部分代码。文中还强调了 switch 语句中 case 常量的唯一性、break 语句的作用以及 switch 语句与 if 语句的区别。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值