3

If we want to have a switch statement where for each case we need to run some instructions then break we would so something like this:

switch (condition) {
   case (opt1):
      // do stuff
      break;
   case (opt2):
      // do stuff
      break;
   case (opt3):  
      // do stuff
      break;
   // ...
   default:
      // do stuff
}

Is it possible to have an exclusive switch, without fall through, where by default every option should break and not have to explicitly state the break instruction? And if not in C++ any idea if such a feature is available in other imperative languages?

Vee6
  • 1,527
  • 3
  • 21
  • 40
  • 8
    There is no such flow control, as [switch statements were designed to allow fallthrough](https://stackoverflow.com/questions/252489/why-was-the-switch-statement-designed-to-need-a-break). You could use `if`/`else if`/`else` (at the expense of slight performance loss) if you want to avoid the `break` – Cory Kramer Jun 29 '15 at 14:59
  • To have that, you'd have to eliminate fall through, and why would you want to do that? It's too handy a feature. – Rob K Jun 29 '15 at 15:33
  • I would probably want that type of derivate form of the swich statement in order to improve code readability and let's say row space. As an extended language feature. – Vee6 Jun 29 '15 at 15:37
  • 1
    @Vee6 `any idea if such a feature is available in other imperative languages?` Pascal / Delphi – PaulMcKenzie Jun 29 '15 at 15:52

3 Answers3

3

C# needs the break too, but yells at you if you don't put it. You need to goto label; to explicitly fall through.

In C++, there is no way to do this natively (other than horrible macros, of course). However, Clang has the -Wimplicit-fallthrough warning. You can then insert [[clang::fallthrough]]; to silence the warning for a deliberate fallthrough.

Documentation : http://clang.llvm.org/docs/AttributeReference.html#fallthrough-clang-fallthrough

Quentin
  • 62,093
  • 7
  • 131
  • 191
2

I hate having break statements in my switches, so I use the pattern of wrapping a switch in a closure and returning from each case. For example:

auto result = [&] {
  switch(enum_val) {
    case A:
      return Foo();
    case B:
      return Bar();
  }
}();
Andrew
  • 897
  • 1
  • 9
  • 19
0

"There is no automatic fall through" in Golang. https://golang.org/doc/effective_go.html#switch

B.I.
  • 706
  • 3
  • 9
  • 19