cv16列克星敦:switch 语句中 当若干分支需要执行相同操作时,可以使多个case分支共用一组语句。

来源:百度文库 编辑:查人人中国名人网 时间:2024/05/13 02:21:52
如何理解“执行相同的操作”“一组”,语法形式如何

switch(i)
{
case 0:
case 1:
case 2:
cout<<"Hello world!"<<endl;
}
//当i=0,1,2时,都有相同的输出。

switch(i)的语法很特殊.每一个case后的值和switch(i)中的i值比,相同就执行这个分支.但执行每个分支结束时,一般都加上break;这样就跳出了switch语句.但你要把"多个case分支共用一组语句"这样就可以把break去掉.像楼上所编的那样...
看看这个:
#include<stdio.h>
void main()
{
switch(0)
{
case 0: printf("i=0\n");
case 1: printf("i=1\n");break;
case 2: printf("i=2\n");
//default: printf("other\n");
}
switch(1)
{
case 0: printf("i=0\n");
case 1: printf("i=1\n");break;
case 2: printf("i=2\n");
//default: printf("other\n");
}
}