用箭头代码重构无限循环

问题描述

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

// 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语句中,您是否建议重组此无限循环?

解决方法

重写它看起来很简单:

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

counter = 0;

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