前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >C++核心准则ES.78:不要依靠switch语句的隐式下沉处理

C++核心准则ES.78:不要依靠switch语句的隐式下沉处理

作者头像
面向对象思考
发布2020-06-09 14:58:48
7680
发布2020-06-09 14:58:48
举报

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(示例)

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:

一个语句中包含多个标签是没有问题的。

switch (x) {
case 'a':
case 'b':
case 'f':
    do_something(x);
    break;
}

Return statements in a case label are also OK:

case标签中使用返回语句也没有问题:

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]]记法明确标明。

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

本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2020-06-05,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 面向对象思考 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • ES.78: Don't rely on implicit fallthrough in switch statements
  • Reason(原因)
    • Note(注意)
      • Enforcement(实施建议)
      领券
      问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档