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:?

3
  • 1
    This isn't an Arduino specific question and it was already answered on SO.
    – gre_gor
    Aug 10, 2018 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, 2018 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, 2018 at 15:29

1 Answer 1

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.