class Program
{
static void Main(string[] args)
{
Test(0);
}
static void Test(int i)
{
if (i > 30000)
{
return;
}
Test(i + 1);
}
}
Why getting recursive function and throwing StackOverflowException when calling this above sample.
(Because over the default recursive stack size ?)
but i wonder how to solve this problem .
Thanks.
You’re getting an exception because 30,000 stack frames is a rather large number 🙂
You solve it by using recursion in a more circumspect manner. The ideal problems to be solved recursively are those which reduce the “search space” quickly (a).
For example, binary tree traversal where your search space is halved each time you recur:
Adding two unsigned integers (and your own algorithm above) are not a good fit for recursion because you’ll blow out your stack allocation long before the results are calculated.:
(a) Search space can be defined as your entire set of possible answers. You want to reduce it as quickly as possible.
And , as an aside, the ideal problems for recursion have nothing to do with stack space in a theoretical/mathematical sense, they’re just any problem that can be expressed as:
(“simple” , in this sense, means approaching the terminating condition).
Theoretical/mathemeatical approaches wouldn’t need to take stack space into account but we, as computer scientists, must. Reality sets limits 🙂
See also When would I not use recursion? and Situations where you would convert recursion to iteration.