Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 446
sharp12345 Avatar asked Dec 29 '12 20:12

sharp12345


1 Answers

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++);
   }
like image 125
itadapter DKh Avatar answered Oct 27 '22 00:10

itadapter DKh