Why is this an issue?
Recursion happens when control enters a loop that has no exit. This can happen a method invokes itself, when a pair of methods invoke each other,
or when goto
statements are used to move between two segments of code. It can be a useful tool, but unless the method includes a
provision to break out of the recursion and return
, the recursion will continue until the stack overflows and the program crashes.
Noncompliant code example
int Pow(int num, int exponent) // Noncompliant; no condition under which pow isn't re-called
{
num = num * Pow(num, exponent-1);
return num; // this is never reached
}
void WhileLoop() // Noncompliant; no condition under which while loop would exit
{
while (true)
{
var line = Console.ReadLine();
Console.WriteLine(line);
}
}
void InternalRecursion(int i)
{
start:
goto end;
end:
goto start; // Noncompliant; there's no way to break out of this method
}
Compliant solution
int Pow(int num, int exponent)
{
if (exponent > 1) // recursion now conditional and stop-able
{
num = num * Pow(num, exponent-1);
}
return num;
}
void WhileLoop()
{
string line;
while ((line = Console.ReadLine()) != null) // loop has clear exit condition
{
Console.WriteLine(line);
}
}