为什么这个递归不会产生StackOverFlowException?

sha*_*345 10 .net c# stack-overflow recursion csc

这段代码有什么问题:

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

我使用这个命令编译这段代码:

csc /warn:0 /out:app4noex.exe app4.cs
Run Code Online (Sandbox Code Playgroud)

当我双击exe时,它似乎没有抛出异常(StackOverFlowException),并且永远保持运行.

使用visual studio命令提示符2010,但我也在系统上安装了vs 2012,都是最新的.

ita*_*DKh 10

因为优化器将尾递归调用展开为:

    static void fn1()
    {
      START:

        Console.WriteLine(x++);
        GOTO START;
    }
Run Code Online (Sandbox Code Playgroud)

重写以获得如下异常:

   static int y;

   static void fn1()
   {
       Console.WriteLine(x++);
       fn1();
       Console.WriteLine(y++);
   }
Run Code Online (Sandbox Code Playgroud)

  • 由未获得例外的作者验证.但尾递归是一个众所周知的优化,现在CLR抖动呢?根据它的确如此. (2认同)