switch-case statement without break

后端 未结 7 1681
鱼传尺愫
鱼传尺愫 2021-02-04 01:44

According to this book I am reading:

Q What happens if I omit a break in a switch-case statement?

A The break statement enables program execution to exit the swi

7条回答
  •  日久生厌
    2021-02-04 01:49

    I've seen in many comments and answers that it's a bad practice to omit break lines. I personally find it very useful in some cases.

    Let's just take a very simple example. It's probably not the best one, just take it as an illustration:
    - on bad login, you need to log the failed attempt.
    - for the third bad attempt, you want to log and do some further stuff (alert admin, block account, ...).

    Since the action is the same for first and second try, no need to break between these two and rewrite the same commands a second time.
    Now the third time, you want to do other things AND also log. Just do the other things first, then let it run (no break) through the log action of the first and second attempts:

    switch (badCount) {
        case 3: //only for 3
            alertAdmin();
            blockAccount();
        case 2: //for 2 AND 3
        case 1: //for 1 AND 2 and 3
            errorLog();
            badCount++;
    }
    

    Imho, if it was soooo bad practice to have common code for different cases, the C structure would simply NOT allow it.

提交回复
热议问题