Reputation: 709
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.
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. 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
Upvotes: 1
Views: 118
Reputation: 19855
++
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.
Upvotes: 4