gsa*_*ras 19 c break switch-statement
假设这个示例代码(源代码):
#include <stdio.h>
void playgame()
{
printf( "Play game called" );
}
void loadgame()
{
printf( "Load game called" );
}
void playmultiplayer()
{
printf( "Play multiplayer game called" );
}
int main()
{
int input;
printf( "1. Play game\n" );
printf( "2. Load game\n" );
printf( "3. Play multiplayer\n" );
printf( "4. Exit\n" );
printf( "Selection: " );
scanf( "%d", &input );
switch ( input ) {
case 1: /* Note the colon, not a semicolon */
playgame();
break;
case 2:
loadgame();
break;
case 3:
playmultiplayer();
break;
case 4:
printf( "Thanks for playing!\n" );
break;
default:
printf( "Bad input, quitting!\n" );
break;
}
getchar();
return 0;
}
Run Code Online (Sandbox Code Playgroud)
我们应该break;在最后一个 default案例中使用a 吗?如果我删除它,我会看到程序的相同行为.但是,我看到其他例子还使用了break;在default案件.
为什么?有原因吗?
Dav*_*eri 43
我们应该休息一下吗?在最后的默认情况下?
来自C编程语言 - 第二版(K&R 2):
第3.4章开关
作为一个好的形式,在最后一个案例(默认在这里)之后休息,即使它在逻辑上是不必要的.有一天,当最后添加另一个案例时,这一点防御性编程将为您节省开支.
首先,你应该考虑为什么我们应该break在switch语句中使用.看看这个不破坏的开关语句.
switch ( input ) {
case 1: /* Note the colon, not a semicolon */
playgame();
case 2:
loadgame();
case 3:
playmultiplayer();
case 4:
printf( "Thanks for playing!\n" );
default:
printf( "Bad input, quitting!\n" );
}
Run Code Online (Sandbox Code Playgroud)
假设input == 1.该程序将调用playgame()当然,但因为没有break,程序将无法完成switch,但呼吁loadgame(),playmultiplayer()两个printf小号顺序.
为避免这种情况,我们使用break.
case 1:
playgame();
break; /* here */
case 2:
...
Run Code Online (Sandbox Code Playgroud)
因为break,程序switch在运行代码之前完成语句case 2.这是我们的预期结果,不是吗?
你的开关是这样的:
switch ( input ) {
case 1: /* Note the colon, not a semicolon */
playgame();
break;
case 2:
loadgame();
break;
case 3:
playmultiplayer();
break;
case 4:
printf( "Thanks for playing!\n" );
break;
default:
printf( "Bad input, quitting!\n" );
break;
}
Run Code Online (Sandbox Code Playgroud)
由于没有case年代后default,有没有效果,你是否写break上default与否.但是,您可以轻松地编写一个新案例.
default:
printf( "Thanks for playing!\n" );
/* what happens if there's no `break`...? */
case 5:
the_new_feature();
break;
}
Run Code Online (Sandbox Code Playgroud)
这是C/C++中的常见错误.如果你在5年后添加新功能并且你完全忘记它,它将成为一个非常错误的 bug.一些现代语言(例如C#,......)甚至禁止没有break或没有开关盒return.
结论:语法没有问题,但是非常糟糕的做法和break强烈建议使用.
这取决于如何编写 default case。
在以下情况下,中断是必要的。
switch ( input ) {
default:
printf( "Bad input, quitting!\n" );
break;
case 1: /* Note the colon, not a semicolon */
playgame();
break;
case 2:
loadgame();
break;
Run Code Online (Sandbox Code Playgroud)