Hao Shen
Hao Shen

Reputation: 2745

Use reference argument in recursive function in C++

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.

Upvotes: 3

Views: 5638

Answers (2)

Ben Voigt
Ben Voigt

Reputation: 283733

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.

Upvotes: 1

Mike Woolf
Mike Woolf

Reputation: 1210

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.

Upvotes: 1

Related Questions