在 C语言 中,想要实现逻辑选择语句,拥有两种途径,if-else 多路选择分支,switch 语句。
我们可以从下面的案例中进行探究。
/*
if_else.c
if-else 多路选择结构
BeginnerC
*/
#include <stdio.h>
int main()
{
int choose;
scanf("%d", &choose);
if (1 == choose)
{
printf("You choose one.\n");
}
else if (2 == choose)
{
printf("You choose two.\n");
}
else
{
printf("You choose another.\n");
}
return 0;
}
而将这个简单的程序改写成 switch 语句,则可以变成如下的形式。
/*
switch.c
使用 switch 进行多路判断
BeginnerC
*/
#include <stdio.h>
int main()
{
int choose;
scanf("%d", &choose);
switch (choose)
{
case 1:
{
printf("You choose one.\n");
break;
}
case 2:
{
printf("You choose two.\n");
break;
}
default:
{
printf("You choose another.\n");
break;
}
}
return 0;
}
相较于 if,switch 语句在 逻辑的选择判断上 有着更出色的性能与更良好的可读性。