关于C语言,switch/case使用方法无需太多的介绍了,此次主要介绍一个良好注释的应用,方便程序后续调试以及bug的修复。
/***********************************************
* Fuction: 输入成绩,判断成绩的等级,比如90~100分属于等级A.
* Aim:为了说明FALL THROUGH的作用
* Author: Chen Jiang
* Modify Date: 2018.04.08
* *********************************************/
#include <stdio.h>
int main()
{
int score = 0;
printf("Please enter a score:\n");
scanf("%d",&score);
switch(score/10)
{
case 10:
/* FALL THROUGH */
case 9:
printf("You score level is A\n");
break;
case 8:
printf("You score level is B\n");
break;
case 7:
/* FALL THROUGH */
case 6:
printf("You score level is C\n");
break;
default:
printf("You score level is D\n");
break;
}
return 0;
}
如果程序出现bug,其他程序维护人员看到没有break的代码,可能会误认为执行条件少了break语句,从而引起更多的bug,如果在语句中加入FALL THROUGH的注释,表明该case语句确实不需要break中断语句,从而提醒其他维护人员此处逻辑正确。