C++核心准则ES.78:不要依靠switch语句的隐式下沉处理
发布日期:2021-07-01 05:28:28 浏览次数:2 分类:技术文章

本文共 1800 字,大约阅读时间需要 6 分钟。

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 fallthroughcase 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

 


 

新书介绍

以下是本人3月份出版的新书,拜托多多关注!

 

本书利用Python 的标准GUI 工具包tkinter,通过可执行的示例对23 个设计模式逐个进行说明。这样一方面可以使读者了解真实的软件开发工作中每个设计模式的运用场景和想要解决的问题;另一方面通过对这些问题的解决过程进行说明,让读者明白在编写代码时如何判断使用设计模式的利弊,并合理运用设计模式。

对设计模式感兴趣而且希望随学随用的读者通过本书可以快速跨越从理解到运用的门槛;希望学习Python GUI 编程的读者可以将本书中的示例作为设计和开发的参考;使用Python 语言进行图像分析、数据处理工作的读者可以直接以本书中的示例为基础,迅速构建自己的系统架构。

 

觉得本文有帮助?欢迎点赞并分享给更多的人。

阅读更多更新文章,请关注微信公众号【面向对象思考】

转载地址:https://oothinking.blog.csdn.net/article/details/107673673 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:C++核心准则ES.79:使用default处理一般case
下一篇:C++核心准则ES.77:循环中尽量少用break和continue

发表评论

最新留言

路过,博主的博客真漂亮。。
[***.116.15.85]2024年04月13日 07时41分59秒