Saturday, May 22, 2010

How can i keep my variables from changing in a recursive function in C++? (when returning back to main)?

Hi,





This is my code:





int MinIndex (int iArray[], int minI, int startI, int numElements)


{





if (iArray[startI] %26lt; iArray[minI] %26amp;%26amp; numElements %26gt; 1)


{


minI = startI;





return MinIndex(iArray, minI, startI + 1, numElements - 1);


}


else


return minI;





}





What I want to do is return the minimum number in an array using recursion. minI is set to 0, while startI is set to 1.





The debugging appears to work fine until the first if statement ends. When elseing, it goes back to the recursive call and starts mixing up the variables.





I know that recursion works on a stack, but I'm not sure how keep minI the same. Any ideas?





Thanks





Epic

How can i keep my variables from changing in a recursive function in C++? (when returning back to main)?
What your doing is passing the value of minl to the next instance of the function which is a copy of the one set in the previous instance. When you set minl the local copy is changed but all instances aren't. So each time you return minl you aren't returning the final minl but the local copy. You have 3 options to having minl change across all instances of the function on the stack whenever you set it.





1) Global


2) Static


3) Pointers





Pointers is your best bet but will require you to figure out a way of creating the variable only once.





The easy way out would to make a global minl variable. But I will be stoned by all other programmers for even suggesting it.


No comments:

Post a Comment