Should we break the default case in switch statement?

后端 未结 7 1488
北荒
北荒 2020-12-15 16:51

Assuming this example code (source):

#include 

void playgame()
{
    printf( \"Play game called\" );
}
void loadgame()
{
    printf( \"Load g         


        
7条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-15 17:33

    For one thing, you should think about why we should use break in switch statement. Look at this no-breaking switch statement.

    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" );
    }
    

    Suppose input == 1. The program will call playgame() of course, but since there's no break, program won't finish the switch but call loadgame(), playmultiplayer(), two printfs sequentially.

    To avoid this, we use break.

    case 1:
        playgame();
        break; /* here */
    case 2:
        ...
    

    Because of break, the program finishes switch statement before running codes of case 2. That's our expected result, isn't it?

    Your switch is this:

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

    Since there's no cases after default, there's no effect whether you write break on default or not. However, you can easily suppose to write a new case.

        default:
            printf( "Thanks for playing!\n" );
            /* what happens if there's no `break`...? */
        case 5:
            the_new_feature();
            break;
    }
    

    It's common-mistakes in C/C++. If you add new feature after 5 years and you completely forget it, it'll become a very buggy bug. Some modern language (e.g. C#, ...) even forbid switch-case without break or return.

    Conclusion: There's no problem in syntax, but it's very bad practice and using break is highly recommended.

提交回复
热议问题