开发者

A Question About Looping

开发者_如何转开发
while(thingA is true)
{
}
if(thingA is not true)
{
    make thingA true
    then back to looping
}

My question is if the looping is true it will keep looping but if it's not I will go through aonther code to make it true, after that I want it to loop again. Can I do that!?


My question is, if you want to loop until something is false, then once it's false set to true and re-loop, why check the condition at all? Why not just:

while (true)
{
    if (thingA is not true)
    {
        // do whatever you want 
    }
}

My point just being, if all you want to do is make it true and re-loop, why stop looping at all?


What you're describing will loop forever, regardless of the value of thingA (you'll always end up back in the loop). If you need to take some action when the state of thingA changes, then you simply need:

while (1)
{
    if (!thingA) { /* Some action */ }
    ...
}


The code block you have provided is effectively an infinite loop. The reason is because thingA remains true through the while loop, until it evaluates to false and breaks out of the loop. Then it is checked by an if statement that checks to see if it is false - it has to be, or the while loop would not have been broken. Then you loop some more.

Just check for thingA being false inside an infinite loop and execute your special case logic.


Instead of rearranging your code in the same function, try to move common code to a separate function. This will make your code easier to understand and the flow easier to follow.

In your case you probably want something like this:

void MyLoopFunction()
{
bool MyCheckVariable = true;
while (MyCheckVariable)
   {
   ...
   }
}

void SomeOtherFunction()
{
// Keep executing until infinity
while (true)
   {
   MyLoopFunction();
   // Fell out of the loop, do something else and retry
   ...
   }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜