Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Switch statement with returns -- code correctness [closed]

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 breaks 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"?

like image 252
houbysoft Avatar asked Jun 17 '10 20:06

houbysoft


People also ask

Can switch-case have return statement?

The JavaScript switch statement can contain return statements if it is present inside a function.

What is not allowed in a switch statement?

The value of the expressions in a switch-case statement must be an ordinal type i.e. integer, char, short, long, etc. Float and double are not allowed. The case statements and the default statement can occur in any order in the switch statement.

Which is true about switch statement?

The statements in a switch continue to execute as long as the condition at the top of the switch remains true.

Can you put code after a return statement?

The only way you could usefully have code after a "return" is if the "return" statement is conditional. This isn't great coding style, you're creating code where there are 2+ ways to exit. When you need to debug it you'll find it more challenging to put in flags and "what happened when we exited" and so forth.


2 Answers

Remove the break statements. They aren't needed and perhaps some compilers will issue "Unreachable code" warnings.

like image 184
kgiannakakis Avatar answered Oct 11 '22 03:10

kgiannakakis


I would take a different tack entirely. Don't RETURN in the middle of the method/function. Instead, just put the return value in a local variable and send it at the end.

Personally, I find the following to be more readable:

String result = "";  switch (something) { case 0:   result = "blah";   break; case 1:   result = "foo";   break; }  return result; 
like image 36
NotMe Avatar answered Oct 11 '22 04:10

NotMe