Udostępnij za pośrednictwem


Recursive Procedures

A recursive procedure is one that calls itself. In general, this is not the most effective way to write Visual Basic code.

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 
        Return 1
    Else 
        Return factorial(n - 1) * n
    End If 
End Function

Considerations with Recursive Procedures

Limiting Conditions. You must design a recursive procedure to test for at least one condition that can terminate the recursion, and you must also handle the case where no such condition is satisfied within a reasonable number of recursive calls. Without at least one condition that can be met without fail, your procedure runs a high risk of executing in an infinite loop.

Memory Usage. Your application has a limited amount of space for local variables. Each time a procedure calls itself, it uses more of that space for additional copies of its local variables. If this process continues indefinitely, it eventually causes a StackOverflowException error.

Efficiency. You can almost always substitute a loop for recursion. A loop does not have the overhead of passing arguments, initializing additional storage, and returning values. Your performance can be much better without recursive calls.

Mutual Recursion. You might observe very poor performance, or even an infinite loop, if two procedures call each other. Such a design presents the same problems as a single recursive procedure, but can be harder to detect and debug.

Calling with Parentheses. When a Function procedure calls itself recursively, you must follow the procedure name with parentheses, even if there is no argument list. Otherwise, the function name is taken as representing the return value of the function.

Testing. If you write a recursive procedure, you should test it very carefully to make sure it always meets some limiting condition. You should also ensure that you cannot run out of memory due to having too many recursive calls.

See Also

Tasks

Troubleshooting Procedures

Troubleshooting Exceptions: System.StackOverflowException

Concepts

Procedures in Visual Basic

Sub Procedures

Function Procedures

Property Procedures

Operator Procedures

Procedure Parameters and Arguments

Procedure Overloading

Loop Structures

Reference

StackOverflowException