简体   繁体   中英

StackOverflowException in recursive interpreter written in C#

I'm trying to create a simple interpreter in C#. My idea was using recursion. So i have this function:

void InterpretLine(int lineIndex, string[] lines)
{
    // Do interpreter stuff

    InterpretLine(lineIndex + 1, lines);
}

As you can see this uses recursion. I did this using recursion because then i wouldn't have to deal with function stacks and stuff. This works for less than 100 lines of input code, but if it reaches too much lines, this throws a System.StackOverflowException .

Are there any better ways instead of recursion?

You are going to have to change your logic to not use recursion for reading each line. If you use recursion you will add a new function call to the stack for every layer of recursion, and the prior function calls will not be removed until the exit condition is met. If you make it 500 or so calls deep you can expect a stackoverflow exception.

Now, I don't have time to read over your code, but I can tell you what you need to do: Turn your recursive call into a loop.

Your code can probably be broken down into something like this:

void ExecuteProgramLine(int lineNumber)
{
   InterpretAndRunLine(lineNumber);
   ExecuteProgramLine(lineNumber + 1);
}

You will want to convert that to this:

for(int lineNumber = 0; lineNumber < fileLines) // (foreach loop is probably better)
{
    InterpretAndRunLine(lineNumber);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM