使用外部方法从循环中断

org*_*lce 2 c++ loops arduino

我正在用Arduino编程,我的程序包含很多while循环.当Arduino收到一个角色时,它必须进行一些计算并从它收到角色时所处的循环中断开.我将给你一个更简单的例子(假设i和j设置为0):

while (i < 256)
{
    // some calculations #1
    i++;

    if (Serial.available() > 0)
    {
        setStringOne = "string one"
        setStringTwo = "string two"
        setStringThree = "string three"
        setStringFour = "string four"

        break;
    }
}

while (j < 256)
{
    // some calculations #2
    j++;

    if (Serial.available() > 0)
    {
        setStringOne = "string one"
        setStringTwo = "string two"
        setStringThree = "string three"
        setStringFour = "string four"

        break;
    }
}
Run Code Online (Sandbox Code Playgroud)

您可以看到,在这两种情况下,我在if语句中使用了相同的代码.我希望它能够写出这样的东西.

while (i < 256)
{
    // some calculations #1
    i++;

    if (Serial.available() > 0)
        checkAndBreak();
}

while (j < 256)
{
    // some calculations #2
    j++;

    if (Serial.available() > 0)
        checkAndBreak();
}

void checkAndBreak()
{
    if (Serial.available() > 0)
    {
        setStringOne = "string one"
        setStringTwo = "string two"
        setStringThree = "string three"
        setStringFour = "string four"

        break;
    }
}
Run Code Online (Sandbox Code Playgroud)

用外部方法打破循环.

它给了我一个错误"break语句不在循环或开关中",这是预期的,因为它不知道要从哪个循环中断,但我只是想知道是否有可能沿着这些行做出一些东西.

提前致谢!

B.M*_*.M. 6

你不能那样打破,所以没办法.只需平衡每种方法的作用:

while (i < 256)
{
      if (Serial.available() > 0)
      {
             setThoseStrings();
             break;
      }
      i++;
}
Run Code Online (Sandbox Code Playgroud)

另外

while (i < 256)
{
        if (checkSerialAndSetStrings())
        {
               break;
        }
        i++;
}
Run Code Online (Sandbox Code Playgroud)

这看起来更短但是如果您需要在其他情况下设置字符串(例如,在计时器用完时设置它们),您将浪费时间从序列检查中删除序列检查checkSerialAndSetStrings并更新代码.我会选择#1.