The friends who have read my previous blog know that function calls rely primarily on the stack interaction of EBP and ESP. So the main feature of recursion is that the function calls itself. If a function calls itself, then this function is a recursive function.
We can look at the invocation of the normal function. Imagine if function A calls function B, and function B calls function C, then how does the data in the stack be saved?
function a ^ function B | (address decrement) function C |
If it is a recursive function, take a simple recursive function as an example:
int iterate (int value) {if (value = = 1) return 1;return value + iterate (value-1);}
Let's use a function to make a call and see what happens.
void process () {int value = iterate (6);}
See what the memory stack is like now?
Iterate (int 1) line 96iterate (Int. 2) line + bytesiterate (Int. 3) line + bytesiterate (Int. 4) line + Bytesi Terate (int 5) line + bytesiterate (Int. 6) line + bytesprocess () line 102 + 7 Bytesmain () line 108mainCRTStartup () line 206 + byteskernel32! 7c817067 ()
As you can see from the code above, there is no difference between a recursive function and a normal function. In addition to calling itself, he is a normal function. So when does this function go back? This is the key to the recursive function. We see that the iterate function stops at 1, so the stack above (value = = 1) is return. So the most critical part of a recursive function is two points: (1) recursion strategy; (2) function exit.
As you can see here, you may feel that the recursive function is the same. But there is one more thing to keep in mind, the depth of recursion is a problem we must consider. Only the recursion depth is within a controllable range, then the entire recursive process is controllable. When is it not to be controlled? Is that recursion depth exceeds a certain number? Is this number related to the specific thread stack length? When the stack overflows, the data obtained is lost in authenticity and therefore meaningless.
Let's generalize the above question, how can we use our own stack to simulate the recursive calls above? This satisfies both recursive properties and the ability to control the depth of the function.
You can first write your own plan, below is just my personal idea.
int iterate (int value) {int count = 0;int number =0;push (value); while ( -1! = (number = pop ())) {if (1! = number) push (Numbe R-1); count + = number;} return count;}
C + + (recursion and Stack)