C语言学习之switch分支结构
在C语言中,除了用“if...else...”以及三目运算“表达式1?表达式2:表达式3”来完成选择执行语句的方式外,还可以用switch(表达式)分支结构来进行选择性执行语句,在学习时有几点要特点要注意的点:
1、语法结构:
switch(表达式)
{case 常量表达式1:语句1;[break];
case 常量表达式2:语句2;[break];
...
case 常量表达式n:语句n;[break];
[default:语句n 1;[break];]
}
A、在此语法中,case 中的常量表达式必须是一个常量值,不可以是变量,如1,2或3 2等常量。如:
#include<stdio.h>
main()
{
int n ;
printf("please input a number:\n");
scanf("%d",&n); switch(n)
{
case 1:printf("result is one.\n");break;
case 2:printf("result is two .\n");break;
case 1 2:printf("result is three.\n");break;
//相当于case 3: :printf("result is three.\n");break;
}
}
输入2,则结果为:result is two .
B、case 语句后的break;语句根据情况需要还写上,如果执行完这个情况,需要结束则必须要加上break;语句,表达中断这个switch结构,跳出到switch的最后的“}”后执行,当case 语句后没有加上break;语句时,则系统会继续往下执行,一直到碰到break;语句或执行到最后为止。如:
#include<stdio.h>
main()
{
int n ;
printf("please input a number:\n");
scanf("%d",&n); switch(n)
{
case 1:printf("result is one.\n");//后面没有break;语句,则执行完此语句后,仍会往后执行。
case 2:printf("result is two .\n");break;
case 1 2:printf("result is three.\n");break;
}
}
输入:1,则结果为:result is one.
result is two.
C、case 后的表达式不一定要按顺序来写,如可以写成这样:
#include<stdio.h>
main()
{
int n ;
printf("please input a number:\n");
scanf("%d",&n);
switch(n)
{
case 1:printf("result is one.\n");break;
case 3:printf("result is three.\n");break;
case 2:printf("result is two .\n");break;
}
}
D、default 语句表示没有找到与case中相同的常值时才执行default后的语句,根据情况可写可不写,并且可以写在switch结构中的任何地方。如:
#include<stdio.h>
main()
{
int n ;
printf("please input a number:\n");
scanf("%d",&n);
switch(n)
{case 1:printf("result is one.\n");break;
case 3:printf("result is three.\n");break;
case 2:printf("result is two .\n");break;
default: printf("result is other.\n");break;
}
}
或者是:
#include<stdio.h>
main()
{
int n ;
printf("please input a number:\n");
scanf("%d",&n);
switch(n)
{case 1:printf("result is one.\n");break;
default: printf("result is other.\n");break;
case 3:printf("result is three.\n");break;
case 2:printf("result is two .\n");break;
}
}
E、在case 表达式:后面的语句可以多条,可以不用“{}”括起来。
#include<stdio.h>
main()
{
int n ;
printf("please input a number:\n");
scanf("%d",&n);
switch(n)
{case 1:printf("result is one.");printf("\n");break; //case中包含多条语句
default: printf("result is other.\n");break;
case 3:printf("result is three.\n");break;
case 2:printf("result is two .\n");break;
}
}
F:在switch中可以让多个case情况执行同一条语句,则只需把需要执行的语句写在最后一个case 语句中,其它的加上空语句即可,但不能写成:case 1,2,4:printf("It is OK!");如:
#include<stdio.h>
main()
{
int n ;
printf("please input a number:\n");
scanf("%d",&n);
switch(n)
{//让结果是1,4,5,7时执行同一条语句
case 1:
case 4:
case 5:
case 7:printf("result is right.\n");break;
default: printf("result is other.\n");break;
case 3:printf("result is three.\n");break;
case 2:printf("result is two .\n");break;
}
}
,