A recursive procedure is a procedure that calls itself. But know that a loop construct usually can do the same work more satisfactorily.
The procedure that follows uses recursion to calculate the factorial of its initial argument.
Function factorial(n As Int) As Int Return If n <= 1 Then 1 Else n * factorial(n - 1) End Function
- Limits on execution
- A recursive procedure must contain a test that can stop recursion, and with the smallest number of recursive calls possible. Without these, there is a risk of an infinite loop.
- Memory limits
- Your program has a space in memory for its local variables.
Each time a procedure calls itself, it uses some of this memory to keep copies of local variables.
If this process continues for too long, then the space will decrease until none is remaining.
The result is a run-time error,
- A loop is usually a better alternative to recursion. A procedure call must pass arguments, initialize storage, and return a result. A loop has none of this overhead.
- Mutual recursion
- Two procedures can call each other. This can have the same problems as usual recursion, but not as easy to find and debug.