0

Curiosity question, and pretty simple.

Assuming I have a while loop, and the last piece of code executed inside this loop is a switch statement, should I finish my case blocks with break, or with continue?

The result of the execution is virtually the same as far as I can tell. Is one of them faster? Are there weird edge cases?

while (ShouldLoop)
{
     switch (myInt)
     {
         case 0:
             doStuff();
             break; // or continue?
         default:
             break; // that is the question.
     }
 }
Kilazur
  • 3,089
  • 1
  • 22
  • 48

2 Answers2

2

Almost certainly you should be finishing your case statement blocks with break. Consider the two scenarios:

  • If all that's important is you don't fall through to the below case statements then you should use break.
  • You've provided an incomplete code sample and there could be code following the switch statement which you want to skip on certain cases. In this scenario a continue statement would be more appropriate than the above scenario, but this is already sounding a bit like spaghetti. If this were the case you'd probably be better setting a boolean variable in your case statement block and using a break. Then you could wrap the following code with an if statement on this boolean flag.

It's a bit subjective because both 'work', but one has much clearer intent IMO.

simon-pearson
  • 1,601
  • 8
  • 10
2

continue will always act on the enclosing while loop, no matter where you place it in your code, instructing the compiler to continue with the next evaluation of the ShouldLoop while stopping execution of any code after the continuation. On the other hand, break acts differently whether you place it at the 1st level of your while loop where it would simply exit the loop, whereas placing it inside of switch-case would stop evaluation and exit the switch-case once the compiler encounters the keyword.

As @simon-pearson pointed out, there might be cases where continue inside switch-case would make sense, but that definitely is not a readable code and such use-cases should be replaced by some other workaround. Usually, switch-case should be written with break.

faithfull
  • 431
  • 6
  • 8