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

I want to check the condition inside the loop and execute the code block when it first met. After this, the cycle may be repeated, but the block should be ignored. Is there a sample for this? Of course, it is easy to declare a flag outside the loop. But I'm interested in an approach that lives entirely inside the loop.

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

bool flag = true; for (;;) { if (someCondition() && flag) { // code that runs only once flag = false; } // code that runs every time } 
+6
source share
5 answers

These are pretty hacks, but as you said, this is the main application loop, I assume it is in the call-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 }); ::: } 
+10
source

For a less complicated version of Mobius answer:

 while(true) { // some code that executes every time for(static bool first = true;first;first=false) { // some code that executes only once } // some more code that executes every time. } 

You can also write this using ++ on bool, but it seems to be deprecated .

+7
source

a possibly cleaner way to write this, albeit with a variable, would be as follows

 while(true){ static uint64_t c; // some code that executes every time if(c++ == 0){ // some code that executes only once } // some more code that executes every time. } 

static allows you to declare a variable inside the loop in which IMHO looks cleaner. If your code, which is executed every time, makes some verifiable changes, you can get rid of the variable and write it like this:

 while(true){ // some code that executes every time if(STATE_YOUR_LOOP_CHANGES == INITIAL_STATE){ // some code that executes only once } // some more code that executes every time. } 
+3
source

If you know that you want to run this loop only once, why not use break as the last statement in the loop.

0
source
 1 while(true) 2 { 3 if(someCondition()) 4 { 5 // code that runs only once 6 // ... 7 // Should change the value so that this condition must return false from next execution. 8 } 9 10 // code that runs every time 11 // ... 12 } 

If you expect code without an external flag, you need to change the value of the condition in the last statement of the condition. (7th line in the code fragment)

-1
source

Source: https://habr.com/ru/post/949649/


All Articles