0

The Arduino Switch Case Reference has a switch structure written two different ways:

First in the Syntax as:

switch (var) {
  case label1:
    // statements
    break;
  case label2:
    // statements
    break;
  default:
    // statements
}

and then in the Example code as:

  switch (var) {
    case 1:
      //do something when var equals 1
      break;
    case 2:
      //do something when var equals 2
      break;
    default:
      // if nothing else matches, do the default
      // default is optional
      break;
  }

Is there any reason to (or not to) add a break; in the default: case? Does the need for 'break;' change if the final case is not default:?

closed as off-topic by gre_gor, sempaiscuba, Greenonline, per1234, Juraj Aug 12 '18 at 18:21

This question appears to be off-topic. The users who voted to close gave this specific reason:

  • "This question does not appear to be about Arduino, within the scope defined in the help center." – gre_gor, sempaiscuba, Greenonline, per1234, Juraj
If this question can be reworded to fit the rules in the help center, please edit the question.

  • 1
    This isn't an Arduino specific question and it was already answered on SO. – gre_gor Aug 10 '18 at 15:15
  • 2
    break is an exit command, since the loop is exiting anyway, you do not need it ..... you should use it though because you may cut/paste code, or add another case statement after the last case statement, and also to form a habit to use it in case statements in general – jsotola Aug 10 '18 at 15:23
  • 1
    I'd like to argue that this is Arduino specific because not all C++ rules apply to an Arduino. For example, the lack of an exception system prevents Try and catch. – ATE-ENGE Aug 10 '18 at 15:29
2

You can, but you don't have to.

Should you? That's up to you.

I do. That's because it's then simple to add another case at the end of the structure in the future if you want, and you don't have to remember to add the break to the existing last case.

Not the answer you're looking for? Browse other questions tagged or ask your own question.