3

Is there a standard or widely accepted term for referring to a variable within the current call of a recursive function where the last value of the same variable is passed as an argument? I am trying to comment a complex recursive function and I feel as if there is going to be a communication barrier between how well I'm explaining it and terminology I use.

Here's some example code:

Foo(0);

void Foo(int oldValue)
{
    // I need to know how to refer to "currentValue" / "oldValue" when commenting
    int currentValue = oldValue + 1;

    if (currentValue == 10)
        return;
    else
        Foo(currentValue);
}

I anticipate some people to just say refer to the variables by their names but I want to be able to refer to them by a generic name (eg: the value) and dicern the 2 by context (eg: current recursive iteration value / last recursive iteration value)

Maybe I'm overthinking it, I'd just like to know if such a term exists to better document for my team

  • 3
    Can't think of any general terms but I think using "previous" would be pretty clear. Of course none of it makes sense viewed in context of initial function call because there were no calls before that. – user1242967 Apr 6 '16 at 19:38
4

I suggest passing in the current value as the function's parameter. It should operate on that value and maybe recurse, computing new values to pass to the recursive calls.

A function is easier to explain and more reusable if it takes responsibility for its own operations and goes from there rather than assuming it's called recursively from one particular place and computing its argument value from that stack frame's value.

Adjusting your example:

void Foo(int value)
{
    if (value == 10)
        return;
    Foo(value + 1);
}

Your terminology and explanations will benefit from this, furthermore from giving a more meaningful name to the function parameter than value or currentValue and from computing the recursive arguments with more meaning in the problem domain than "the value for the next iteration."

E.g. a flood-fill function will recolor the current pixel and recursively call itself on the four neighboring pixels:

void FloodFill(Image image, int x, int y, Color targetColor, Color replacementColor) {
  if (image.get(x, y) == replacementColor) {
    return;
  }
  if (image.get(x, y) != targetColor) {
    return;
  }

  image.set(x, y, replacementColor);

  FloodFill(image, x, y - 1, targetColor, replacementColor); // 1 step south
  FloodFill(image, x, y + 1, targetColor, replacementColor); // north
  FloodFill(image, x - 1, y, targetColor, replacementColor); // east
  FloodFill(image, x + 1, y, targetColor, replacementColor); // west
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.