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
}
                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.
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.
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.
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 });
  :::
}
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With