首页 > 解决方案 > 用箭头代码重构无限循环

问题描述

我有一个具有一定周期(延迟)的无限循环。我有以下结构:

// define the i32threshold of time
// set i32counter to 0
while(true)
{
  if(bExecuteEnable)
  {
    if(bConnectionSet)
    {
      if(++i32counter >= i32threshold)
      {
        // Do the job
        counter = 0;
      }
    }
  }

  delay(1); // 1 ms of delay introduces the period
}

if除了将所有条件合并到单个语句中之外,您是否有任何建议来重构这个无限循环?

标签: c++c++11if-statement

解决方案


重写它看起来简单了很多:

while (!bExecuteEnable && !bConnectionSet && ++i32counter < i32threshold) {
  delay(1); // 1 ms of delay introduces the period
}

counter = 0;

当然希望i32threshold小于您的最大值,i32counter否则您将永远溢出并循环。


推荐阅读