[英]Why does the ++ operator cause a stack overflow in my recursive method yet +1 does not?
So I just took a CS test at school tonight and I had to write a recursive method that found the max value in an array. 因此,我今晚才在学校参加了CS测试,我不得不写一个递归方法来在数组中找到最大值。
This is what I came up with: 这是我想出的:
public static int getMax(int[] a, int max, int index)
{
if(index == a.length)
{
return max;
}
if(a[index] > max)
{
max = a[index];
}
return getMax(a, max, index++);
}
That's what I put on the paper I turned in, but lo and behold I get home and put it in my IDE to try it out and see if it works and I get a stack overflow. 那就是我在上交的纸上放的东西,但是瞧瞧我回到家并将其放在我的IDE中进行尝试,看看它是否有效,并且我得到了堆栈溢出的信息。 So I do some testing and finally change the second return to: 因此,我做了一些测试,最后将第二个返回值更改为:
return getMax(a, max, index+1);
and no more stack overflow. 并且没有更多的堆栈溢出。
Why does the ++
operator break the method? 为什么++
运算符会破坏该方法?
Thanks 谢谢
++
in suffix form increments after the variable is evaluated. 在评估变量后 ,后缀形式的++
递增。 You're passing the current value of the index into your recursive call, then incrementing it locally back in the parent function. 您正在将索引的当前值传递到递归调用中,然后在父函数中本地将其递增。 In other words, you keep passing the same index value into deeper and deeper recursive calls until you run out of stack. 换句话说,您一直将相同的索引值传递给越来越多的递归调用,直到用完堆栈。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.