Avoiding Infinite Recursion






Avoiding Infinite Recursion

It's possible to call procedures in such a way that a continuous loop occurs. Consider the following two procedures:

public static void DoSomething()
{
    DoSomethingElse();
}
public static void DoSomethingElse()
{
    DoSomething();
}

Calling either of these procedures produces an infinite loop of procedure calls and results in the error shown in Figure.

11. Infinite recursion results in a stack overflow exception (error).


This endless loop is known as a recursive loop. Without getting too technical, Visual C# allocates some memory for each procedure call in an area known as the stack. Only a finite amount of space is available on the stack, so infinite recursion eventually uses all the available stack space, and an exception occurs. This is a serious error, and steps should be taken to avoid such recursion.

Legitimate uses exist for recursion, most notably in the use of algorithms such as those used in calculus or those used to iterate through all of the folders on a hard drive. Deliberate recursion techniques don't create infinite recursion, however; there is always a point at which the recursion stops (hopefully, before the stack is consumed). If you have an interest in such algorithms, consider reading a book dedicated to the subject.



 Python   SQL   Java   php   Perl 
 game development   web development   internet   *nix   graphics   hardware 
 telecommunications   C++ 
 Flash   Active Directory   Windows