Abanoub
Abanoub

Reputation: 3809

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!?

Upvotes: 1

Views: 159

Answers (4)

Patrick
Patrick

Reputation: 23619

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
   ...
   }
}

Upvotes: 0

James
James

Reputation: 5425

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.

Upvotes: 1

Oliver Charlesworth
Oliver Charlesworth

Reputation: 272467

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 */ }
    ...
}

Upvotes: 2

James Michael Hare
James Michael Hare

Reputation: 38397

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?

Upvotes: 5

Related Questions