A recursive procedure is one that calls itself. For example, the following procedure uses recursion to calculate the factorial of its original argument:
Function Factorial(ByVal N As Integer) As Integer If N <= 1 Then ' Reached end of recursive calls. Return 1 ' N = 0 or 1, so climb back out of calls. Else ' N > 1, so call Factorial again. Return Factorial(N - 1) * N End If End Function
Note When a Function procedure calls itself recursively, the procedure name must be followed by parentheses, even if there is no argument list. Otherwise, the function name is taken as representing the return value of the function.
Programs have a limited amount of space for variables. Each time a procedure calls itself, more of that space is used. If this process continues indefinitely, it eventually causes a stack space error. The cause may be less obvious if two procedures call each other indefinitely, or if a condition that limits the recursion is never met.
You should test your recursive procedure to make sure it does not call itself indefinitely, or so many times that you run out of memory. You can often substitute loops for recursion.