1

我在一个类似于这样的函数中有一个 do-while 循环:

do
{
    // a bunch of stuff
    if (something < something else)
    {
        return true;
    }
    else if (stuff > other stuff)
    {
        if (something != other stuff)
        {
             return false;
        }
        else
        {
              return true;
         }
     }
} while (condition);

我的问题是condition最后。我可以跟踪这一点的唯一方法是在循环之前声明一个布尔变量,并将其值设置为与该return值匹配并while()在每次迭代后对其进行检查。虽然这可行,但对我来说似乎相当不雅,我想知道是否有一种方法可以让我while()利用return价值。

4

3 回答 3

2

目前尚不清楚您的情况如何。无论如何,您可能想要一个无限循环:

for (; ;) {
    … your code here …
}

或者:

while (true) {
    … your code here …
}

这个循环永远不会自行停止......但是因为你使用它退出它return不是问题。

于 2011-03-18T15:02:49.310 回答
1

假设由于您试图解释它而导致您的代码不正确,那么您应该这样做以满足您对返回的需求与while();

对其他人来说,下面的代码是不正确的逻辑,但我试图将其保留在他使用的类似伪代码中。基本上,如果您希望 while 模拟返回值,则需要!return 才能退出条件。

do
{
    // a bunch of stuff
    if (something < something else)
    {
        return !condition;
    }
    else if (stuff > other stuff)
    {
        if (something != other stuff)
        {
             return condition;
        }
        else
        {
              return !condition;
        }
    }
} while (condition);
于 2011-03-18T15:07:02.453 回答
0

你可以说

 do
{
    // a bunch of stuff
    if (something < something else)
    {
        return true;
    }
    else if (stuff > other stuff)
    {
        if (something != other stuff)
        {
             return false;
        }
        else
        {
              return true;
         }
     }
     else if(exit_condition)
      break;
} while (1);
于 2011-03-18T15:05:49.717 回答