lojzezust
lojzezust

Reputation: 13

Recursion restarting loop (C++)

I have a question regarding C++. So I have made this program, that computes all possible combinations to solve a problem using recursion(instead of 9 loops). This is a part of the code:

int used[9];
nMin=1000;

void Combinations(int index)
    {
      if(index>8)
      {
        return;
      }
      for(int i=k;i<4;i++)
      {
        used[index]=i;
        if (sum<nMin && Check())//Checks the solution
        {
          nMin = sum;
          used[i]=0;
          return;
        }
        else
        {
          Combinations(index+1);
        }
      }
}

The for loop, that should repeat 4 times resets every time recursive call returns. In other words the loop variable is set to 0. Is that just how it works, and do I have to store current loop variable value, or is there another way.

Edit: thank you guys, for detailed information and your answers. The code worked after a few tweaks.

Upvotes: 0

Views: 490

Answers (2)

Alain
Alain

Reputation: 27240

int i is a local variable that exists within the context of that for loop for that instance of that function call. When you make a recursive call to the same function, you're pushing a brand new instance of that function call on the stack, which has its own for loop with its own int i variable. They are in no way connected to each other.

If you want all recursive calls to the function to share a counter, you will need to define it as a static variable, and define it outside of the scope of the for loop, like this:

void Combinations(int index)
{
     static int persistentCounter;

This will maintain it's value in recursive calls.

Upvotes: 2

Mike Kwan
Mike Kwan

Reputation: 24457

If I am reading this correctly, your question is whether the loop variable i will be protected/preserved by the recursive calls to Combinations.

The answer is yes, the value of the loop counter will be preserved. The reason is scope. Each time the function is called, the stack creates space for a new variable i scoped to the current call. This means all interactions with i during a function call are with the i created for that specific call.

Note: The C/C++ language standards have no explicit notion of a stack. This is actually an implementation detail for the implementation of automatic storage.

Upvotes: 2

Related Questions