如何从开关内部跳出循环?

本文介绍了如何从开关内部跳出循环?的处理方法,对大家解决问题具有一定的参考价值

问题描述

我正在编写一些看起来像这样的代码:

I'm writing some code that looks like this:

while(true) {
    switch(msg->state) {
    case MSGTYPE: // ... 
        break;
    // ... more stuff ...
    case DONE:
        break; // **HERE, I want to break out of the loop itself**
    }
}

有什么直接的方法吗?

我知道我可以使用一个标志,并通过在切换后放置一个条件中断来中断循环.我只是想知道 C++ 是否已经为此提供了一些构造.

I know I can use a flag, and break from the loop by putting a conditional break just after the switch. I just want to know if C++ has some construct for this already.

推荐答案

前提

无论语言或所需功能如何,都应将以下代码视为错误格式:

Premise

The following code should be considered bad form, regardless of language or desired functionality:

while( true ) {
}

支持论据

while( true ) 循环的形式很差,因为它:

Supporting Arguments

The while( true ) loop is poor form because it:

  • 打破了 while 循环的隐含契约.
    • while 循环声明应明确声明 only 退出条件.
    • Breaks the implied contract of a while loop.
      • The while loop declaration should explicitly state the only exit condition.
      • 必须阅读循环内的代码才能理解终止子句.
      • 永远重复的循环会阻止用户从程序中终止程序.
      • 有多个循环终止条件,包括检查真".
      • 无法轻松确定将始终在每次迭代中执行的代码放置在何处.
      • 要查找错误、程序复杂性分析、安全检查或在不执行代码的情况下自动导出任何其他源代码行为,指定初始中断条件允许算法确定有用的不变量,从而改进自动源代码分析指标.
      • 如果每个人都对非无限循环使用 while(true),那么当循环实际上没有终止条件时,我们就失去了简洁交流的能力.(可以说,这已经发生了,所以这一点没有实际意义.)
      • If everyone always uses while(true) for loops that are not infinite, we lose the ability to concisely communicate when loops actually have no terminating condition. (Arguably, this has already happened, so the point is moot.)

      下面的代码是更好的形式:

      The following code is better form:

      while( isValidState() ) {
        execute();
      }
      
      bool isValidState() {
        return msg->state != DONE;
      }
      

      优势

      没有标志.没有转到.没有例外.容易改变.易于阅读.易于修复.另外代码:

      Advantages

      No flag. No goto. No exception. Easy to change. Easy to read. Easy to fix. Additionally the code:

      1. 将循环工作负载的知识与循环本身隔离开来.
      2. 允许维护代码的人轻松扩展功能.
      3. 允许在一处指定多个终止条件.
      4. 将终止子句与要执行的代码分开.
      5. 对核电站来说更安全.;-)

      第二点很重要.在不知道代码如何工作的情况下,如果有人让我让主循环让其他线程(或进程)拥有一些 CPU 时间,我会想到两种解决方案:

      The second point is important. Without knowing how the code works, if someone asked me to make the main loop let other threads (or processes) have some CPU time, two solutions come to mind:

      准备好插入暂停:

      while( isValidState() ) {
        execute();
        sleep();
      }
      

      选项 #2

      覆盖执行:

      void execute() {
        super->execute();
        sleep();
      }
      

      此代码比嵌入了 switch 的循环更简单(因此更易于阅读).isValidState 方法应该只确定循环是否应该继续.该方法的主力应该被抽象为 execute 方法,它允许子类覆盖默认行为(使用嵌入式 switchgoto).

      This code is simpler (thus easier to read) than a loop with an embedded switch. The isValidState method should only determine if the loop should continue. The workhorse of the method should be abstracted into the execute method, which allows subclasses to override the default behaviour (a difficult task using an embedded switch and goto).

      对比 StackOverflow 上发布的以下答案(针对 Python 问题):

      Contrast the following answer (to a Python question) that was posted on StackOverflow:

      1. 永远循环.
      2. 要求用户输入他们的选择.
      3. 如果用户的输入是重新启动",则永远继续循环.
      4. 否则,永远停止循环.
      5. 结束.

      代码

      while True: 
          choice = raw_input('What do you want? ')
      
          if choice == 'restart':
              continue
          else:
              break
      
      print 'Break!' 
      

      对比:

      1. 初始化用户的选择.
      2. 在用户选择重启"时循环.
      3. 要求用户输入他们的选择.
      4. 结束.

      代码

      choice = 'restart';
      
      while choice == 'restart': 
          choice = raw_input('What do you want? ')
      
      print 'Break!'
      

      这里,while True 会导致误导和过于复杂的代码.

      Here, while True results in misleading and overly complex code.

      这篇关于如何从开关内部跳出循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,WP2

admin_action_{$_REQUEST[‘action’]}

do_action( "admin_action_{$_REQUEST[‘action’]}" )动作钩子::在发送“Action”请求变量时激发。Action Hook: Fires when an ‘action’ request variable is sent.目录锚点:#说明#源码说明(Description)钩子名称的动态部分$_REQUEST['action']引用从GET或POST请求派生的操作。源码(Source)更新版本源码位置使用被使用2.6.0 wp-admin/admin.php:...

日期:2020-09-02 17:44:16 浏览:1158

admin_footer-{$GLOBALS[‘hook_suffix’]}

do_action( "admin_footer-{$GLOBALS[‘hook_suffix’]}", string $hook_suffix )操作挂钩:在默认页脚脚本之后打印脚本或数据。Action Hook: Print scripts or data after the default footer scripts.目录锚点:#说明#参数#源码说明(Description)钩子名的动态部分,$GLOBALS['hook_suffix']引用当前页的全局钩子后缀。参数(Parameters)参数类...

日期:2020-09-02 17:44:20 浏览:1060

customize_save_{$this->id_data[‘base’]}

do_action( "customize_save_{$this->id_data[‘base’]}", WP_Customize_Setting $this )动作钩子::在调用WP_Customize_Setting::save()方法时激发。Action Hook: Fires when the WP_Customize_Setting::save() method is called.目录锚点:#说明#参数#源码说明(Description)钩子名称的动态部分,$this->id_data...

日期:2020-08-15 15:47:24 浏览:798

customize_value_{$this->id_data[‘base’]}

apply_filters( "customize_value_{$this->id_data[‘base’]}", mixed $default )过滤器::过滤未作为主题模式或选项处理的自定义设置值。Filter Hook: Filter a Customize setting value not handled as a theme_mod or option.目录锚点:#说明#参数#源码说明(Description)钩子名称的动态部分,$this->id_date['base'],指的是设置...

日期:2020-08-15 15:47:24 浏览:885

get_comment_author_url

过滤钩子:过滤评论作者的URL。Filter Hook: Filters the comment author’s URL.目录锚点:#源码源码(Source)更新版本源码位置使用被使用 wp-includes/comment-template.php:32610...

日期:2020-08-10 23:06:14 浏览:925

network_admin_edit_{$_GET[‘action’]}

do_action( "network_admin_edit_{$_GET[‘action’]}" )操作挂钩:启动请求的处理程序操作。Action Hook: Fires the requested handler action.目录锚点:#说明#源码说明(Description)钩子名称的动态部分$u GET['action']引用请求的操作的名称。源码(Source)更新版本源码位置使用被使用3.1.0 wp-admin/network/edit.php:3600...

日期:2020-08-02 09:56:09 浏览:870

network_sites_updated_message_{$_GET[‘updated’]}

apply_filters( "network_sites_updated_message_{$_GET[‘updated’]}", string $msg )筛选器挂钩:在网络管理中筛选特定的非默认站点更新消息。Filter Hook: Filters a specific, non-default site-updated message in the Network admin.目录锚点:#说明#参数#源码说明(Description)钩子名称的动态部分$_GET['updated']引用了非默认的...

日期:2020-08-02 09:56:03 浏览:854

pre_wp_is_site_initialized

过滤器::过滤在访问数据库之前是否初始化站点的检查。Filter Hook: Filters the check for whether a site is initialized before the database is accessed.目录锚点:#源码源码(Source)更新版本源码位置使用被使用 wp-includes/ms-site.php:93910...

日期:2020-07-29 10:15:38 浏览:825

WordPress 的SEO 教学:如何在网站中加入关键字(Meta Keywords)与Meta 描述(Meta Description)?

你想在WordPress 中添加关键字和meta 描述吗?关键字和meta 描述使你能够提高网站的SEO。在本文中,我们将向你展示如何在WordPress 中正确添加关键字和meta 描述。为什么要在WordPress 中添加关键字和Meta 描述?关键字和说明让搜寻引擎更了解您的帖子和页面的内容。关键词是人们寻找您发布的内容时,可能会搜索的重要词语或片语。而Meta Description则是对你的页面和文章的简要描述。如果你想要了解更多关于中继标签的资讯,可以参考Google的说明。Meta 关键字和描...

日期:2020-10-03 21:18:25 浏览:1688

谷歌的SEO是什么

SEO (Search Engine Optimization)中文是搜寻引擎最佳化,意思近于「关键字自然排序」、「网站排名优化」。简言之,SEO是以搜索引擎(如Google、Bing)为曝光媒体的行销手法。例如搜寻「wordpress教学」,会看到本站的「WordPress教学:12个课程…」排行Google第一:关键字:wordpress教学、wordpress课程…若搜寻「网站架设」,则会看到另一个网页排名第1:关键字:网站架设、架站…以上两个网页,每月从搜寻引擎导入自然流量,达2万4千:每月「有机搜...

日期:2020-10-30 17:23:57 浏览:1294