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 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;
}