You're doing an addition after calling yourself. Tail recursion means absolutely nothing can be after
If you understand the implementation, it's clear why.
Say we call count
for the first time from main
, which is at program counter 0xAAA
. It then does most of its method. We'll say the recursive call to count is at 0xBBB
for this stack frame. If you're using tail recursion, when calling itself, it can set the return address as 0xAAA
(just go straight to the code that called me). If it's doing anything after, it must set the return address as 0xBBC
(the address of the addition). Because it doesn't need stack frames to store return addresses, it's also much easier to transform the recursion to iteration. When count
calls itself, it can just jump to the beginning of the method.
The solution (to the trivial example) is to build up the result in another parameter:
int count(int x, int res) {
if(x<=0) return res;
return count(x - 1, res + 1);
}
Note we do nothing after.