Search code examples
c#.netrecursionstack-overflowcsc

Why doesn't this recursion produce a StackOverFlowException?


What is wrong with this code:

using System;
namespace app1
{
    static class Program
    {
        static int x = 0;
        static void Main()
        {
            fn1();
        }
        static void fn1()
        {
            Console.WriteLine(x++);
            fn1();
        }
    }
}

I compile this piece of code using this command:

csc /warn:0 /out:app4noex.exe app4.cs

When I double click on the exe, it doesn't seem to throw the exception (StackOverFlowException), and keep running forever.

Using visual studio command prompt 2010, but I also have vs 2012 installed on the system, all up to date.


Solution

  • Because the optimizer unrolls the tail recursion call into:

        static void fn1()
        {
          START:
    
            Console.WriteLine(x++);
            GOTO START;
        }
    

    Rewrite to get exceptions like so:

       static int y;
    
       static void fn1()
       {
           Console.WriteLine(x++);
           fn1();
           Console.WriteLine(y++);
       }