0

Sorry if this is the wrong site, but let's imagine a function (C#):

public int Increment(int i)
{
    int j = i;
    if (j++ < Math.Pow(10, 12)) j = Increment(j);

    return j;
}

The function is pretty useless, but it's just an example. I would imagine that the final recursion return value of the self recursion "loop" would pass the result back down through each recursive function, returning each method to the previous recursion, before finally returning back to the initial function call, returning to the caller of the function.

My question is how many recursions we can have, and what causes that limit? Thanks.

Nick Bull
  • 9,518
  • 6
  • 36
  • 58

1 Answers1

5

Close to 100,000. However, if you are ever in danger of reaching that limit, you should redesign your code to remove the recursion.

Also, thought I'd note that int.MaxValue is about 2.1*10^9 (2.1 billion), which is less than 10^12, so (even disregarding recursion limits) your function would never return. When you try to increment from j == int.MaxValue, you'll either throw an exception (if you're in a checked environment) or loop back to j == int.MinValue (if unchecked).

Community
  • 1
  • 1
Tim S.
  • 55,448
  • 7
  • 96
  • 122