Yakku
Yakku

Reputation: 449

Change for loop condition with respect to an external flag (cpp)

I have a code block as following, where the inner for loop code remains the same but only the loop condition changes based on the reverseFlag. Is there a better way to code this without having to copy paste the content of the for loop twice ?

bool reverseFlag=false;

if (reverseFlag)
{
    for(int i = 1; i < TotalFrames; i++)
    {...}
}
else
{
    for(int i = TotalFrames-1; i >0; i--)
    {...}
}

Upvotes: 2

Views: 889

Answers (2)

Karoly Horvath
Karoly Horvath

Reputation: 96266

There are several options. You can:

  • Use two loops but put the loop body in a separate function/object/lambda.. to avoid duplication.
  • Use an increasing loop and calculate the real index within the loop:

    j = reverseFlag ? TotalFrames - i : i; 
    
  • Pre-calculate the loop conditions as @dasblinkenlight suggested.

Note that if you have a performance critical loop, some of these methods could hurt performance. If in doubt, check what your compiler does and measure the elapsed time.

Upvotes: 1

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726849

Yes, you can do it in a single for loop, like this:

int from, to, step;
if (reverseFlag) {
    from = TotalFrames-1;
    to = -1;
    step = -1;
} else {
    from = 0;
    to = TotalFrames;
    step = 1;
}
for (int i = from ; i != to ; i+= step) {
    ...
}

A single conditional ahead of the loop prepares loop's parameters - i.e. its starting and ending values and the step, and then the loop uses these three values to iterate in the desired direction.

Upvotes: 4

Related Questions