什么是default在C语言中
default是C语言中的一个关键字,用于switch语句中的默认分支。当switch语句中的所有case分支都不匹配时,程序会执行default分支中的代码。
default用法示例
下面是一个使用default的示例:
#include <stdio.h>
int main()
{
int num = 3;
switch(num)
{
case 1:
printf("num is 1\n");
break;
case 2:
printf("num is 2\n");
break;
default:
printf("num is not 1 or 2\n");
break;
}
return 0;
}
在上面的示例中,变量num的值为3,不匹配任何一个case分支,因此执行default分支中的代码,输出“num is not 1 or 2”。
default的注意事项
在使用default时,需要注意以下几点:
- default分支可以放在任何位置,但通常放在最后。
- default分支可以没有任何代码,只是一个空语句。
- default分支不是必需的,可以省略。
- default分支只能有一个。
- default分支可以和case分支一样使用break语句,也可以没有。
在实际使用中,需要根据具体情况灵活使用default分支。
