Let's say I have code in C with approximately this structure:
switch (something)
{
case 0:
return "blah";
break;
case 1:
case 4:
return "foo";
break;
case 2:
case 3:
return "bar";
break;
default:
return "foobar";
break;
}
Now obviously, the "break"s are not necessary for the code to run correctly, but it sort of looks like bad practice if I don't put them there to me.
What do you think? Is it fine to remove them? Or would you keep them for increased "correctness"?
Interesting. The consensus from most of these answers seems to be that the redundant
break
statement is unnecessary clutter. On the other hand, I read thebreak
statement in a switch as the 'closing' of a case.case
blocks that don't end in abreak
tend to jump out at me as potential fall though bugs.I know that that's not how it is when there's a
return
instead of abreak
, but that's how my eyes 'read' the case blocks in a switch, so I personally would prefer that eachcase
be paired with abreak
. But many compilers do complain about thebreak
after areturn
being superfluous/unreachable, and apparently I seem to be in the minority anyway.So get rid of the
break
following areturn
.NB: all of this is ignoring whether violating the single entry/exit rule is a good idea or not. As far as that goes, I have an opinion that unfortunately changes depending on the circumstances...
I think the *break*s are there for a purpose. It is to keep the 'ideology' of programming alive. If we are to just 'program' our code without logical coherence perhaps it would be readable to you now, but try tomorrow. Try explaining it to your boss. Try running it on Windows 3030.
Bleah, the idea is very simple:
/* Just a minor question though. How much coffee have you had while reading the above? I.T. Breaks the system sometimes */
I'd normally write the code without them. IMO, dead code tends to indicate sloppiness and/or lack of understanding.
Of course, I'd also consider something like:
Edit: even with the edited post, this general idea can work fine:
At some point, especially if the input values are sparse (e.g., 1, 100, 1000 and 10000), you want a sparse array instead. You can implement that as either a tree or a map reasonably well (though, of course, a switch still works in this case as well).
Exit code at one point. That provides better readability to code. Adding return statements (Multiple exits) in between will make debugging difficult .
Remove the break statements. They aren't needed and perhaps some compilers will issue "unreachable code" warnings.
I would remove them. In my book, dead code like that should be considered errors because it makes you do a double-take and ask yourself "How would I ever execute that line?"