Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to run code inside a loop only once without external flag?

I want to check a condition inside a loop and execute a block of code when it's first met. After that, the loop might repeat but the block should be ignored. Is there a pattern for that? Of course it's easy to declare a flag outside of the loop. But I I'm interested in an approach that completely lives inside the loop.

This example is not what I want. Is there a way to get rid of the definition outside of the loop?

bool flag = true;
for (;;) {
    if (someCondition() && flag) {
        // code that runs only once
        flag = false;
    }        
    // code that runs every time
}
like image 906
danijar Avatar asked Jul 17 '13 13:07

danijar


People also ask

Which loop will be executed only once?

In the do-while loop, the body of a loop is always executed at least once. After the body is executed, then it checks the condition.

Do While loop only executes once?

There are two variations of the while loop – while and do-While. The difference between the two is that do-while runs at least once. A while loop might not even execute once if the condition is not met. However, do-while will run once, then check the condition for subsequent loops.

How do you stop a code loop?

The purpose the break statement is to break out of a loop early. For example if the following code asks a use input a integer number x. If x is divisible by 5, the break statement is executed and this causes the exit from the loop.


1 Answers

It's fairly hacky, but as you said it's the application main loop, I assume it's in a called-once function, so the following should work:

struct RunOnce {
  template <typename T>
  RunOnce(T &&f) { f(); }
};

:::

while(true)
{
  :::

  static RunOnce a([]() { your_code });

  :::

  static RunOnce b([]() { more_once_only_code });

  :::
}
like image 193
Angew is no longer proud of SO Avatar answered Oct 04 '22 22:10

Angew is no longer proud of SO