Alex Rivera | Logout

break in a case with return.. and for default

Asked 2009-06-05T17:14:51.843
40

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?

Edit
Report

3 Answers

2

I would consider the break after return to be bad form, you will get warnings about unreachable code on some compilers.

The break on your default case is completely appropriate, case fall through is a tool and should be especially marked when used.

answered 2009-06-05T17:21:50.697
2

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.

answered 2009-06-05T18:42:13.750
-1

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.

answered 2009-06-05T17:25:41.127

Your Answer