I know that in C++, arrays are passed by reference and not by value. So if I have a recursive function that accepts an array and an index as arguments, what happens on the recursion?
If I pass the inbound array to an array that is local to the function, will that prevent the recursive calls from operating directly on the initial array? And will a new instance of the local array be created with every recursion?
PS, the array is of maximum length 4 and type int, so I am not worried about memory consumption.
In C++, what happens when a recursive function passes an array to itself?
You can't expect C++ to create a new copy of the array each time, C++ just isn't that sort of language. You would have to create some sort of array copy function, and use that before each recursive call.
Reply:In this situation the initial array will remain untouched, since you will be operating on a local copy. A new local copy will be created for every recursion and they will all stay in scope until your end condition is met, then they will proceed to leave scope in reverse order.
If you do not want to change the initial array but want to see its values, just pass by const reference, using the "const" keyword.
Reply:It seems like you understand the issues, so rather than answer directly, I'll ask a couple of questions.
If the maximum length of the array is four, why don't you just unfold the loop (or whatever) that's operating on the array, and deal with four variables directly?
What is it that you are doing to the array that makes you not want to affect the original copy? Is that the "right" thing to be doing? You're porting something, but you don't have to be a slave to an implementation that was awkward/illogical/dumb, or that was dictated by limitations in the original language. Do you?
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment