What causes this recursive function to crash compared to another nearly identical one?
countForwards(num--)
passes the original value of num
to the recursive call, which means the recursion never ends.
countForwards(--num)
would allow the recursion to end.
After seeing all the traffic this question got, I thought it would be worth it to expand the answer a little.
As paxdiablo commented, even though countForwards(--num)
allows the recursion to terminate, it behaves differently than countForwards(num-1)
.
Both variants would cause the following series of recursive calls :
countForwards(5)
countForwards(4)
countForwards(3)
countForwards(2)
countForwards(1)
countForwards(0)
countForwards(-1)
but they will output a different series of numbers when the recursion unwinds :
num - 1 | -- num |
---|---|
-1 | -1 |
0 | -1 |
1 | 0 |
2 | 1 |
3 | 2 |
4 | 3 |
5 | 4 |
The reason for the difference is that num-1
doesn't change the value of num
while --num
decrements num
.
num--
uses a postfix operator --
which means that original value i.e. num
is passed and its value is decremented after it is passed.
The interesting thing about a postfix operator i.e. the one we are using in this example is that operation is performed and then the value is incremented or decremented. Please refer to official documentation about operators in java
class PrePostDemo {
public static void main(String[] args){
int i = 3;
i++;
// prints 4
System.out.println(i);
++i;
// prints 5
System.out.println(i);
// prints 6
System.out.println(++i);
// prints 6
System.out.println(i++);
// prints 7
System.out.println(i);
}
}
Post-Decrement
Post-Decrement takes the form variable-name operator. This tells the compiler to first use the original value and afterawrds decrement it, so if we have something like this:
for (int i = 10; i > 0; i--)
{
System.out.println(i);
}
The output will be as follows
1: 10
2: 9
3: 8
4: 7
5: 6
6: 5
7: 4
8: 3
9: 2
10: 1
Pre-Decrement
Pre-Decrement takes the form operator variable-name and is used when you want to decrement before you use the value. The same code above would terminate at 0 instead of 1. This is because the function decremented the value before it used the value.
How does this apply to recursive calls?
Each recursive call is it's own stack, so when you pass num-- to the recursive function, you're literally passing the original value of num, and when the child call terminates (in this case never) the parent call will then decrement num. Since you don't have another base case which correctly terminates the call, it results in infinite recursion.