While-loop with pause instead of while (condition)


OK - so maybe I'm tired, but I'm trying figure out a way to do the following (one which seems... more... elegant?)

  • I have a boolean value (we'll call it loopTwice)
  • loopTwice is used by (and modifies the behavior of) the contents of the loop to perform mutually exclusive functions
  • If loopTwice is true, I want the loop to execute twice, first with the value true, then with the value false
  • If loopTwice is false, I want the loop to only execute once, with the value false
  • loopTwice is not used after the loop, so it doesn't matter what the final value is

...that seems to make enough sense, but for some reason, my brain is not coming up with anything more elegant than a while-loop that has an if condition towards the end with a break:

// loopTwice is already set as true or false
while (true) //this seems ugly, not to mention breakable...
    DoThis(loopTwice);          //these act slightly differently based upon loopTwice
    DoThat(loopTwice);          //these act slightly differently based upon loopTwice
    DoAnotherThing(loopTwice);  //these act slightly differently based upon loopTwice

    if (!loopTwice) break;
    loopTwice = false;

This code (well, not this code, but equivalent code...) works exactly as I would like it without provisioning another variable (I guess that's not such a bad thing, but I don't see using another variable making any loop more elegant than this one...)

It seems to me there must be something I'm missing (a way to loop twice if something is true and once if something is false, with the "false" value always being last - and preferably without a second variable, like a counter or a second flag to indicate the loop has already run once).

Is it actually more elegant to use a counter or flag? (I guess with computers of the past several decades, it doesn't really risk breaking memory requirements or anything, does it...). Would breaking this into a function and using recursion be more elegant? hmm...

Elegance, of course, is in the eye of the beholder...

Just to add another method here, recursion!

void MyRecursiveMethod(bool repeat)
   // Do something here.

   // Should we do this more than once?
     MyRecursiveMethod(false); // Don't do this indefinitely!

EDIT: This also allows you to easily extend this to n iterations if necessary, not just two.

For example, in the future you decide you may need to execute this three times, you can change it to int repeatCount instead of a simple bool and then just decrement each time.