2011-03-18 42 views
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值。

+0

此循环是否打算运行,直到它返回真或假里面?还是有更远的回报声明? – DavidMFrey 2011-03-18 15:02:44

+0

似乎没有人理解你的问题,你能清楚吗? – BenjaminB 2011-03-18 15:11:56

回答

1

假设你的代码是不正确因为你想套用它,这是你应该做的事情,以满足您的回报是一样的while();

的需求

对于其他人来说,下面的代码是不正确的逻辑,但我试图将它保留在他使用的类似伪代码中。基本上,如果你想要模仿返回值的时候,你需要退货的!才能退出条件。

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); 
2

目前还不清楚你的情况如何。无论如何,你可能需要一个无限循环:

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

或:

while (true) { 
    … your code here … 
} 

这个循环将永远不会停止本身......不过既然你使用它退出return这是没有问题的。

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);