Switch statement with automatic break at each case step in C++

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?


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


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

链接地址: http://www.djcxy.com/p/14802.html

上一篇: 迭代字典的最佳方法是什么?

下一篇: 在C ++中的每个案例步骤中使用自动中断来切换语句