为什么不是这个递归产生StackOverFlowException? [英] Why doesn't this recursion produce a StackOverFlowException?

查看:172
本文介绍了为什么不是这个递归产生StackOverFlowException?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么是不对的code:

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();
        }
    }
}

我编译这块code。使用这个命令:

I compile this piece of code using this command:

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

当我双击exe文件,它似乎并没有引发异常(StackOverFlowException),并保持运行下去。

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

使用Visual Studio命令提示符2010年,但我也有VS 2012在系统上安装,全部都是最新的。

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

推荐答案

由于优化器展开尾递归调用到:

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++);
   }

这篇关于为什么不是这个递归产生StackOverFlowException?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆