gpt4 book ai didi

c - 我们应该打破 switch 语句中的 default case 吗?

转载 作者:太空狗 更新时间:2023-10-29 16:28:15 25 4
gpt4 key购买 nike

假设此示例代码 ( source ):

#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;
}

我们应该在 last default 情况下使用 break; 吗?如果我删除它,我会看到程序的相同行为。但是,我看到其他示例也在 default 情况下使用了 break;

为什么?有什么原因吗?

最佳答案

Should we use a break; in the last default case?

来自 C 编程语言 - 第二版 (K&R 2):

第3.4章开关

As a matter of good form, put a break after the last case (the default here) even though it's logically unnecessary. Some day when another case gets added at the end, this bit of defensive programming will save you.

关于c - 我们应该打破 switch 语句中的 default case 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26138994/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com