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?
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".
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.
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 aswitch
statement.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.
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.
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.