Tomm
Tomm

Reputation: 127

Is my understanding of how variables work in recursive function correct?

I've recently gotten to recursion in my C++ class and I was wondering is it correct to think that the scope of the variables are local to the specific stack frame:

3) return

2) flipString(" "); begin = a, end = t

1) flipString(at); begin = s, end = r

So when it reaches the return statement it will pop the third frame off,

then the 2nd frame off with s = t + " " + a

and then the first frame with s = r + at + s thus reversing the string.

void flipString(string &s)
{
   if (s.size() < 2)
   {
      return;
   }
   else
   {

      string begin;
      string end;      

      begin = s.at(0);
      end = s.at(s.size()-1);

      s.erase(s.begin());
      s.erase(s.end()-1);

      flipString(s); 

      s = end + s + begin;   
   }

   return;
}

Upvotes: 0

Views: 95

Answers (2)

bill.lee
bill.lee

Reputation: 2375

There are three symbol-types to understand, in this context:

  1. Local variables — symbols declared within a function
  2. Formal parameters — symbols used as parameters within a function's implementation
  3. Actual parameters — expressions passed by the caller on a function's invocation

It is also useful to understand where the values are stored and how the stack works.

A stack-frame is created for each function invocation. This creates a context for the function's execution and a reference to the caller's context. When the function exits, the function's stack frame is removed (popped) and the caller's context is restored.

Formal parameters' locations are reserved in the stack-frame of the function being invoked. Similarly, local variables are stored in the the function's stack-frame. Actual parameters or references to them are copied to the stack where they can be referenced by their formal parameter counterparts.

When the function has exited, the stack-frame is freed up along with the formal parameter and local variable space.

Note that for parameters passed as a reference (&) to actual values, the space for the values may exist outside the current stack-frame (only the reference address, itself, is within the stack-frame. Forgetting this can lean to confusion about why values are persisting across function invocations. This is more obvious with pointers, but may be overlooked when passing references.

Upvotes: 1

Sami Sallinen
Sami Sallinen

Reputation: 3496

Yes, your idea of how the function works and the function itself seem correct.

There is a different instance of the local variables begin and end in each invocation of the function, placed on the stack.

The function argument s references or points to the same string in all stack frames, because, well, it's a reference.

If a plain function argument is passed (without a reference and not as a pointer) there would be a separate copy of that argument too at each call stack level.

Upvotes: 2

Related Questions