4 ms·
I think the best way to explain it is that a recursive function is a function which should return either: - A 'base case' value - The result of a call to itse
by yanickmartel 10y ago
I think the best way to explain it is that a recursive function is a function which should return either:
- A 'base case' value
- The result of a call to itself (could be multiple calls to itself also)
Basically when you call a recursive function, unless it hits the base case (usually decided by an if condition), it will keep calling itself (often with slightly different arguments each time) until it returns the base case.
Once the function returns the base case, the recursion will start to 'unwind' - In the unwind phase, you can use the return values of the previous recursive calls to do more interesting stuff.
The best way to visualize recursion is to imagine that you have a stack of function calls; each time a function calls itself, it creates a copy of itself with new arguments and puts that copy on top of the stack - Then the program pointer moves to the copy (but it keeps a reference of were it was in the previous call) - And it keeps building up the stack with new copies of the function until it reaches the base case (when the function finally returns a concrete value).
The 'unwinding' phase is just when the functions start returning (after the base case has been reached) and all the function 'copies' just get popped off from the top of the stack one by one - Each time the program will continue running from wherever it was in each call stack.