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

danijar picture danijar · Jul 17, 2013 · Viewed 34.4k times · Source

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
}

Answer

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

  :::
}