fall through switch的用法

来源:互联网 发布:招商证券交易软件下载 编辑:程序博客网 时间:2024/04/30 10:41

switch 在其合适的case中开始运行,一直到遇到break或者跳出switch。那么如果你的case中没有break,那就会出现所谓的fall through现象,就像是滑滑梯一样。

 

以下是一段示例程序,有助于你理解fall through:

 

#include "stdio.h"


int main(int argc, char* argv[])
{
 printf("Hello World!/n");

 int num_of_operands = 2;


 //fall through 的设计可以把代码设计得很简约,
 //以下的这个操作数处理是一个很好的例子,它可以很简约的去处理每一个操作数
 //当然不得不说 switch 将 fall through 设计为默认操作是引起许多bug的原因

 //session 1:
 switch(num_of_operands){
 case 2://process_operand(operator->operand_2);
 case 1://process_operand(operator->operand_1);
 default:;
 }

 //session 2:即使是default 没有break,一样会出现fall through现象
 num_of_operands = 2;
 switch(num_of_operands){
 case 1:
  printf("case 1 fall through/n");
 default:
  printf("default fall through/n");
  //num_of_operands = 10;
 case 3:
  printf("case 2 fall through/n");
 
 }

 //conclusion :在使用switch时需要注意,如果是一般应用,请别忘了加上 break

 return 0;
}

 

当然不得不提,fall through 也是很多时候你忘记break带来的bug。