fall through switch的用法
2010-11-17 20:38
716 查看
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。
以下是一段示例程序,有助于你理解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。
相关文章推荐
- Go中的switch fallthrough
- 【swift】15-0525 控制流---switch break continue fallthrough
- switch语句中的Fall-through、静态导入
- 浅谈Swift编程中switch与fallthrough语句的使用
- switch fall-through一题
- java - switch case statement fall through and b...
- Switch Fall Through
- Java中使用switch-case的用法及注意事项
- c#中switch case的用法实例解析
- 2017-05-05 angularjs的ng-switch-when用法
- C# .NET switch case 的用法简介
- Android中ToggleButton,Switch,SeekBar,RatingBar的一些用法
- Go语言中的switch用法实例分析
- switch-case语句用法<转>
- Android的ToggleButton和Switch以及AnalogColok和DigitalColok的用法-android学习之旅(二十)
- c语言基础:关于switch的用法
- 夺命雷公狗—angularjs—5—ng-switch的用法实现下拉更换板块的实现
- themeleaf中的th:switch条件判断语句用法示例
- Java中的Switch用法
- c语言基础switch、if、while和for基本用法