您的位置:首页 > 编程语言 > C语言/C++

C++_Switch Statement

2015-08-07 11:14 344 查看
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.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: