我们应该打破在switch语句的默认情况下? [英] Should we break the default case in switch statement?

查看:230
本文介绍了我们应该打破在switch语句的默认情况下?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设此示例code():

 的#include<&stdio.h中GT;无效琐事()
{
    的printf(玩的游戏叫做);
}
无效loadgame()
{
    的printf(加载游戏名叫);
}
无效playmultiplayer()
{
    的printf(玩多人游戏叫做);
}诠释的main()
{
    INT输入;    的printf(1玩游戏\\ n);
    的printf(2.加载游戏\\ n);
    的printf(三玩多人\\ n);
    的printf(4.退出\\ n);
    输出(选择:);
    scanf函数(%d个,&安培;输入);
    开关(输入){
        案例1:/ *注意冒号,而不是一个分号* /
            玩游戏();
            打破;
        案例2:
            加载游戏();
            打破;
        案例3:
            playmultiplayer();
            打破;
        情况4:
            的printf(谢谢你玩\\ n!);
            打破;
        默认:
            的printf(坏输入,退出\\ N!);
            打破;
    }
    的getchar();    返回0;
}

我们应该使用突破; 最后 默认情况?如果我删除它,我看到程序的行为相同。但是,我看到其他的例子还使用了突破; 默认情况

为什么呢?有没有道理?


解决方案

  

我们应该用休息;在上次的默认情况下?


从的 C编程语言 - 第二版的(K&安培; R 2):

第3.4章交换机


  

作为一种良好形式的问题,把休息的最后案后(默认
  这里)即使它在逻辑上是不必要的。有一天当另一
  案件被加在最后,防御式编程的该位将
  救你。


Assuming this example code (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;
}

should we use a break; in the last default case? If I remove it, I see the same behaviour of the program. However, I saw that other examples also use a break; in the default case.

Why? Is there a reason?

解决方案

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

From The C programming language - Second edition (K&R 2):

Chapter 3.4 Switch

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.

这篇关于我们应该打破在switch语句的默认情况下?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆