Having an infinite loop or recursion will lead to a program failure or a program never finishing the execution.
public int Sum()
{
var i = 0;
var result = 0;
while (true) // Noncompliant: the program will never stop
{
result += i;
i++;
}
return result;
}
This can happen in multiple scenarios.
while and for loops with no break or return statements that have exit conditions which are
always false will be indefinitely executed.
goto statement with nothing that stops it from being executed over and over again will prevent the program from the completion.
When a recursive method call chain lacks an exit condition, the call stack will reach its limit and the program will crash due to a StackOverflowException.
int Pow(int num, int exponent)
{
return num * Pow(num, exponent - 1); // Noncompliant: no condition under which Pow isn't re-called
}
In this example, Pow will keep calling Pow with exponent - 1 forever, until the program crashes with a
StackOverflowException.
Recursion provides some benefits.
However, it has disadvantages as well.
The program’s logic should incorporate a mechanism to break out of the control flow loop. Here are some examples.
false
public int Sum()
{
var i = 0;
var result = 0;
while (true) // Noncompliant: the program will never stop
{
result += i;
i++;
}
return result;
}
public int Sum()
{
var i = 0;
var result = 0;
while (result < 1000)
{
result += i;
i++;
}
return result;
}
goto statements. Instead, you can use a loop statement or explicit
recursion.
public int Sum()
{
var result = 0;
var i = 0;
iteration:
// Noncompliant: program never ends
result += i;
i++;
goto iteration;
return result;
}
public int Sum()
{
var i = 0;
var result = 0;
while (result < 1000)
{
result += i;
i++;
}
return result;
}
int Pow(int num, int exponent)
{
return num * Pow(num, exponent - 1); // Noncompliant: no condition under which Pow isn't re-called
}
int Pow(int num, int exponent)
{
if (exponent > 1) // recursion is now conditional and stoppable
{
num = num * Pow(num, exponent - 1);
}
return num;
}