Recursion happens when control enters a loop that has no exit. It can occur when a method invokes itself, when two methods invoke each other, or
when goto
statements are used to move between two code segments. Recursion can be a useful tool, but unless the method includes a
provision to break out 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: pow is always re-called
num = num * pow(num, exponent-1);
return num; // this is never reached
}
void internalRecursion(int i) {
start:
goto end;
end:
goto start; // Noncompliant: there is no way to break out of this method
}
Compliant solution
int pow(int num, int exponent) {
if (exponent > 1) { // recursion is now conditional and stop-able
num = num * pow(num, exponent-1);
}
return num;
}