1

I have a couple of biggish for loops which I would like to separate into functions to reduce code duplication.

The only difference between them is the first line of the loop.

One is:

for (int j = 50; j < average_diff; j++) {

The other is:

for (int j = upper_limit; j > lower_limit; j--) {

I have an integer, tb which indicates which one I'd like to use (it has a value of 1 or 2 respectively).

I'm wondering how I might best accomplish this. Is this a good use case for macros?

routeburn
  • 1,156
  • 1
  • 12
  • 27
  • `if (cond) { for (first; loop; etc) { function(); } } else { for (second; loop; etc) { function(); } }` –  May 02 '13 at 11:31
  • You might want to extract the loop's body into a function. Or, if possible, change the second loop to `for (int j = lower_limit+1; j <= upper_limit; j++)`. Then you can extract the whole loop to the function. – harpun May 02 '13 at 11:32

3 Answers3

7

Don't wrap the for, just wrap the contents in a function:

for (int j = 50; j < average_diff; j++) {
   process(j);
}

for (int j = upper_limit; j > lower_limit; j--) {
   process(j);
}
Luchian Grigore
  • 253,575
  • 64
  • 457
  • 625
6

No, doesn't sound like a good case for macros at all.

The best (most C++-ish) thing would probably be to use a range, and pass that to the function.

Community
  • 1
  • 1
unwind
  • 391,730
  • 64
  • 469
  • 606
1

If your variable is, like you say, 1 for one direction and 2 for another, you can use the ternary operator ?::

for (int i = (dir == 1 ? 0 : 20);
     dir == 1 ? i < upper_limit :
                i > lower_limit;
     i += (dir == 1 ? 1 : -1))
{
    ...
}

However, it might be more readable if you just use a simple if statement:

if (dir == 1)
{
    for (int i = 0; i < upper_limit; i++)
    {
    }
}
else
{
    for (int i = 20; i > lower_limit; i--)
    {
    }
}

If you go with the last, then I suggest you put the code inside the loop in a separate function that you call, so you don't have any duplicate code.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621