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

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

问题描述

假设这个示例代码(source):

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
" );
    printf( "2. Load game
" );
    printf( "3. Play multiplayer
" );
    printf( "4. Exit
" );
    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!
" );
            break;
        default:
            printf( "Bad input, quitting!
" );
            break;
    }
    getchar();

    return 0;
}

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

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?

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

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

第 3.4 章切换

作为一种良好的形式,在最后一个 case 之后放置一个 break(默认这里),即使它在逻辑上是不必要的.有一天,当另一个案例在最后添加,这一点防御性编程将救你.

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天全站免登陆