3

In a recursive function in C++, one of its argument is reference type. I just want to know what will happen during the recursive call of the function.

Without reference type, I believe every time the function is called recursively, a new variable will be created in the stack. So with the reference, every time what has been created in stack now is some kind of pointer pointing to the address of the original variable where it is declared,right?

So by using reference in such scenario, I believe sometimes we can save some memory.

5
  • IMHO - Avoid recursion in the first place - more trouble than it is worth Commented Feb 1, 2014 at 4:35
  • Yes, internally a pointer is passed. References can be understood as pointers that can't be null. Commented Feb 1, 2014 at 4:37
  • 1
    @Ed: There are places where recursion is the best tool for the job, and avoiding it is more trouble. Commented Feb 1, 2014 at 4:56
  • @BenVoigt - Cannot think of any. Use a stack instead. Or tail recursion that is just a loop Commented Feb 1, 2014 at 5:00
  • 4
    In what way is using a stack to simulate recursion less trouble than using recursion? Commented Feb 1, 2014 at 5:11

2 Answers 2

1

Yes, you've got the right idea. Note, of course, that you only save memory if the parameter type is larger than a pointer. A reference to an integer (or maybe even a double) won't save any memory on the stack.

Sign up to request clarification or add additional context in comments.

Comments

1

Usually parameter values change during recursion. You can't simply share those across all levels.

Furthermore, when a function is not inlined (and recursion interferes with inlining), passing an argument by reference costs as much space as a pointer.

7 Comments

Why not share them across levels? Consider a reference to an object collecting stuff as it goes. BTW How does an inline function and recursion correlate. Surely an inlined function cannot utilize recursion
@Ed: An object "collecting stuff as it goes" is just an explicit stack instead of implicit on call stack. It doesn't fulfill the desire of the question to "save some memory". And I said that recursion interferes with inlining (it prevents inlining beyond a certain depth unless it can be converted to iteration)
It will - instead of aggregating the partial results.
@BenVoigt Yes. I also agree with Ed. Without reference, when we want to repeatedly add something to the "result" argument and finally print the result out, we will "aggregate the partial results".
@Hao: I think Ed may have meant "accumulate", not "aggregate". Aggregation would take less memory than "collecting stuff" for later processing.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.