ES.78: Don't rely on implicit fallthrough in switch statements
ES.78:不要依靠switch语句的隐式下沉处理
Reason(原因)
Always end a non-empty case with a break. Accidentally leaving out a break is a fairly common bug. A deliberate fallthrough can be a maintenance hazard and should be rare and explicit.
通常情况下使用break中止一个非空case处理。意外漏掉某个break通常是一个错误。故意的下沉处理可能带来维护风险,应该少用并明示用法。
Example(示例)
代码语言:javascript复制switch (eventType) {
case Information:
update_status_bar();
break;
case Warning:
write_event_log();
// Bad - implicit fallthrough
case Error:
display_error_window();
break;
}
Multiple case labels of a single statement is OK:
一个语句中包含多个标签是没有问题的。
代码语言:javascript复制switch (x) {
case 'a':
case 'b':
case 'f':
do_something(x);
break;
}
Return statements in a case label are also OK:
case标签中使用返回语句也没有问题:
代码语言:javascript复制switch (x) {
case 'a':
return 1;
case 'b':
return 2;
case 'c':
return 3;
}
Exceptions(例外)
In rare cases if fallthrough is deemed appropriate, be explicit and use the [[fallthrough]] annotation:
在很少的情况下,如果确信下沉处理是合适的,可以使用[[fallthrougn]]记法明确标明。
代码语言:javascript复制switch (eventType) {
case Information:
update_status_bar();
break;
case Warning:
write_event_log();
[[fallthrough]];
case Error:
display_error_window();
break;
}
Note(注意)
Enforcement(实施建议)
Flag all implicit fallthroughs from non-empty cases.
标记所有来自非空case的隐式下沉处理。
原文链接
https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#es78-dont-rely-on-implicit-fallthrough-in-switch-statements