C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
However: The current C# compiler does not achieve this. Each method call frame (activation record) is kept on the stack memory.
And: After nearly 80,000 invocations, the stack memory space is exhausted and the program terminates.
Info: Usually, the StackOverflowException is caused by an infinite or uncontrolled recursion.
C# program that generates StackOverflowException
using System;
class Program
{
static void Recursive(int value)
{
// Write call number and call this method again.
// ... The stack will eventually overflow.
Console.WriteLine(value);
Recursive(++value);
}
static void Main()
{
// Begin the infinite recursion.
Recursive(0);
}
}
Output: truncated
79845
79846
79847
79848
79849
79850
79851
Process is terminated due to StackOverflowException.
And: Such a loop could continue indefinitely because it requires constant space on the stack.
But: The C# compiler was unable to apply this optimization, called tail recursion, in this program.
Warning: This exception is a real risk to all programs—theoretically even those that do not use recursion.