Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Recursion in C#

Are there any general rules when using recursion on how to avoid stackoverflows?

like image 895
Ted Smith Avatar asked Mar 04 '09 14:03

Ted Smith


People also ask

What is the use of recursion in C?

Recursion is the technique of making a function call itself. This technique provides a way to break complicated problems down into simple problems which are easier to solve.

What is the recursion with example?

Recursion is the process of defining a problem (or the solution to a problem) in terms of (a simpler version of) itself. For example, we can define the operation "find your way home" as: If you are at home, stop moving. Take one step toward home.

What is the use of recursion?

Recursion is a technique used to solve computer problems by creating a function that calls itself until your program achieves the desired result.

What is recursion in C and its advantages?

Recursion is the process which comes into existence when a function calls a copy of itself to work on a smaller problem. Any function which calls itself is called recursive function, and such function calls are called recursive calls. Recursion involves several numbers of recursive calls.


1 Answers

How many times you will be able to recurse will depend on:

  • The stack size (which is usually 1MB IIRC, but the binary can be hand-edited; I wouldn't recommend doing so)
  • How much stack each level of the recursion uses (a method with 10 uncaptured Guid local variables will be take more stack than a method which doesn't have any local variables, for example)
  • The JIT you're using - sometimes the JIT will use tail recursion, other times it won't. The rules are complicated and I can't remember them. (There's a blog post by David Broman back from 2007, and an MSDN page from the same author/date, but they may be out of date by now.)

How to avoid stack overflows? Don't recurse too far :) If you can't be reasonably sure that your recursion will terminate without going very far (I'd be worried at "more than 10" although that's very safe) then rewrite it to avoid recursion.

like image 113
Jon Skeet Avatar answered Sep 21 '22 01:09

Jon Skeet