【问题标题】:How to avoid 'while(true)' with 'break' and rather use a 'for' loop?如何使用'break'避免'while(true)',而使用'for'循环?
【发布时间】:2017-03-03 19:21:23
【问题描述】:

我有一个带有配置文件的应用程序,可以从中读取各种设置。其中一项设置是应用程序运行的周期。 如果这个变量nLoops-1,那么它应该运行无限次。否则它将运行x 次。 目前这就是我实现它的方式。但是我想知道是否有没有while(true) 表达式的更直接的方法(我在这里收到警告):

//get nLoops from config file

int i = 0;
while (true)
{
    if (nLoops > -1 && i >= nLoops)
        break;
    i++;

   // do stuff
}

【问题讨论】:

  • 只需将条件放在 while 中,而不是放在 while 中的 if 中
  • 理论上,如果循环要无限运行,则不应不断增加i,因为当您溢出i 时,您会调用未定义的行为。在实践中,您可能会侥幸成功,但请注意这个问题。

标签: c loops if-statement while-loop conditional-statements


【解决方案1】:

只需将if 条件(倒置,因为您测试的是留在而不是突破)在while 条件中:

while (nLoops == -1 || i < nLoops)

或作为for

for (i=0; (nLoops == -1) || (i < nLoops); i++)

【讨论】:

  • 您的 for 循环将执行循环的 stuff 部分,并为 i 设置不同的值,类似于:for (i=0; (nLoops == -1) || (i++ &lt; nLoops); )
  • OP 的nLoops &gt; -1 &amp;&amp; ... 的反转是nLoops &lt;= -1 || ...(假设整数nLoops)。不清楚为什么这个答案使用nLoops == -1
  • @chux 来自问题:如果这个变量nLoops 是-1,那么它应该运行无限次。基于此,原来的条件是错误的。
【解决方案2】:

这需要一个(布尔)变量,但要避免在循环中使用 break 语句。

    // Here reads from configuration file

    bool isInfiniteLoop = false;
    i = 0;

    if(nLoops == -1)
    {
       isInfiniteLoop = true;
       nLoops = 1;
    }

    while(i < nLoops)
    {
         // here goes your code

         if(!isInfiniteLoop)
         {
            // If NOT infinite loop: increment counter, otherwise while condition will always be 0 < 1
            i++;
         }
    }

【讨论】:

    【解决方案3】:

    您可以将while(true) 替换为for(;;) 以避免出现警告。缺少控制表达式的 for 循环在标准中明确定义,例如 ISO/IEC 9899:1999 6.8.5.3/2。

    【讨论】:

      猜你喜欢
      • 2014-01-14
      • 2023-03-27
      • 2012-08-20
      • 1970-01-01
      • 2018-05-26
      • 2021-06-08
      • 1970-01-01
      • 2017-07-14
      • 1970-01-01
      相关资源
      最近更新 更多