break in a case with return.. and for default

2019-01-20 06:58发布

My OCD makes me add "break" when writing case statements, even if they will not be executed. Consider the following code example:

switch(option) {
    case 1:
        a = 1;
        b = 7;
        break;
    case 2:
        a = 2;
        b = 4;
        return (-1);
        break;
    default:
        a = -1;
        break;
}

My two questions are:
For "case 2:", I don't really need the break, but is it a good idea to have it there anyway? For "default:". Is it purely OCD, or is there any real reason to have the break here?

13条回答
做自己的国王
2楼-- · 2019-01-20 07:49

I'm told that in C, C++, java and C#, if you don't put those "breaks" the program code flow will fall into the other "cases" and will execute the instructions inside them, not matter if the variable doesn't have the values assignned to the "cases".

查看更多
一纸荒年 Trace。
3楼-- · 2019-01-20 07:49

I don't personally put the breaks in, but it could help when someone else decides to move the return (-1) to outside of the switch and forgets to add break.

查看更多
成全新的幸福
4楼-- · 2019-01-20 07:50

Please excuse my limited knowledge, but what's OCD?
Apart from that, Brian Kernighan provides a good explanation on when you should (not) use break within a switch statement.

查看更多
劫难
5楼-- · 2019-01-20 07:51

You don't need either break, but there's no harm in having them. In my opinion, keeping your code structured is worth having a couple of extraneous statements.

查看更多
手持菜刀,她持情操
6楼-- · 2019-01-20 07:51

In this exact example, for both questions, it is personal preference. In general, the rule is this: anything without a break will fall through. That means (as Pod said) its a good idea to put breaks in default cases in case they are not last. This also means if your case contains a return, then a following break is indeed not necessary.

查看更多
祖国的老花朵
7楼-- · 2019-01-20 07:56

I prefer always have a break in each case including the default and avoid doing return at all inside switch's. For short switches with just 2-3 cases(including default) return is ok but only if all cases do it the same way. 'pointless' break i see as pointless and only make's it more code to read. Same goes for empty defaults that just do break, totally pointless. The ease to read the code is in my opinion more important that what happens if someone happens to change this or that.

查看更多
登录 后发表回答