Why is an exception thrown to different call numbers?

Consider this code:

private static int i = 0; static void Main(string[] args) { DoSomething(); Console.ReadLine(); } public static void DoSomething() { Console.WriteLine(i); ++i; DoSomething(); } 

Every time I run it, I get a StackOverflowException on a different value of the i variable. For example, 16023, 16200, 16071.

What is the reason for this? Is this a bug in the C # compiler?

+6
source share
2 answers

The behavior of unlimited recursion is determined by implementation. A certain implementation means that he can do something. A program can terminate at any time (or never end), throw an unhandled exception, or something else. For example, compiling in MSIL and working in a 64-bit OS, the program never ends for me. This is because jitter is allowed to turn recursion into a loop that does 64-bit jitter. Asking why it ends with a specific value does not have a practical purpose, since runtime is allowed to do anything.

+5
source

Your stacking is not big enough.

You can increase the default stacking by starting a new thread and define a new stacksize in the constructor:

 using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Threading; namespace ConsoleApplication3 { class Program { private static int i = 0; static void Main(string[] args) { Thread T = new Thread(DoSomething, 100000000); T.Start(); Console.ReadLine(); } public static void DoSomething() { Console.WriteLine(i); ++i; DoSomething(); } } } 

Stackoverflow now comes with 1.5 million recursive calls.

+2
source

Source: https://habr.com/ru/post/947354/


All Articles