Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

break in a case with return.. and for default

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?

like image 952
Alan H Avatar asked Jun 05 '09 17:06

Alan H


2 Answers

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.

like image 64
James Thompson Avatar answered Oct 02 '22 18:10

James Thompson


I agree with having a break in a final default case, and don't agree with breaks after returns. (A colleague does those and it hurts my eyes.)

I also indent switches so as to reduce proliferation of indent levels. :) i.e.:

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

(I also think that, since the return statement is not a function, it isn't appropriate to enforce a superfluous style that makes it look like one.)

like image 28
chaos Avatar answered Oct 02 '22 18:10

chaos