2

Possible Duplicate:
How to write a `for` loop over bool values (false and true)

I want to perform the same task twice with bool flag true first and false second. Is there an elegant way to do that (maybe using a loop)?

My idea was to do something like the following but this is a way too complicated.

bool flag = true;
for(int i = 0; i < 2; ++i, flag = !flag)
{
    // ...
}
Community
  • 1
  • 1
danijar
  • 32,406
  • 45
  • 166
  • 297

4 Answers4

5

Put it in a function, taking flag as an argument. Call the function twice.

Thomas
  • 174,939
  • 50
  • 355
  • 478
  • Definitely the right way! (Passing flag as an argument of course! – Mats Petersson Dec 26 '12 at 12:53
  • 1
    The simplest solution is the best. In my case I would have to pass many variables parameters so I tried avoiding a function for that. But if there is no better solution I would accept your answer. – danijar Dec 26 '12 at 12:54
  • 1
    @sharethis: If you have many related variables, it may be worth thinking about how they could be grouped together into a class. – Mankarse Dec 26 '12 at 12:55
  • 1
    I thought about that but is doesn't make sense in my case and in addition to that my code is strongly performance related. – danijar Dec 26 '12 at 13:04
  • 2
    Did you actually profile your code first? I highly doubt that the function call will make any difference. – Axel Gneiting Dec 26 '12 at 13:17
  • You can always declare the function `inline` if your profiling reveals that it makes any difference. – Thomas Dec 26 '12 at 16:10
4

Since you said you'd have to pass a lot of parameters to the function in Thomas' answer, consider a lambda:

int param1;
bool param2;
...

auto doWork = [&](bool flag){ //<- capture all local variables by reference
    ... do work with params ...
};

doWork(true);
doWork(false);

This way you have your working code encapsulated, don't have to tediously pass any parameters and still have it obvious that you're calling code twice.

s3rius
  • 1,442
  • 1
  • 14
  • 26
3

I figured out a nice way using a do-while-loop.

bool flag = false;
do
{
    // ...
    flag = !flag;
}
while(flag)

Since the code in a do-while-loop is executed at least once, I can toggle the flag at the end and get exactly two runs.

danijar
  • 32,406
  • 45
  • 166
  • 297
2

The solution to call it in a function is probably best, but you can also do:

for( int i = 0; i < 2; ++i ) {
    bool flag = i == 0;
    ...
William Pursell
  • 204,365
  • 48
  • 270
  • 300