java.lang.StackOverflowError due to recursion

前端 未结 10 2251
南方客
南方客 2020-12-03 05:59

My problem is that I usually get a java.lang.StackOverflowError when I use recursion. My question is - why does recursion cause stackoverflow so much more than loops do, and

10条回答
  •  -上瘾入骨i
    2020-12-03 06:43

    The reason why the recursion causes stack overflow is because we fail to establish when the recursion should stop, and thus the function/method will keep calling itself "forever" (until it causes the error). You will have the same problem even if you are using loops, if you have something as the following:

    bool flag = true;
    while (flag == true){
       count++;
    }
    

    Since flag will always be true, the while loop will never stop until it gives you the stack overflow error.

提交回复
热议问题