c++ - Is this function really tail-recursive? -
i read recursion in programming interviews exposed (3rd ed.) present following recursive factorial
function:
int factorial(int n){ if (n > 1) { /* recursive case */ return factorial(n-1) * n; } else { /* base case */ return 1; } }
on bottom of same page (page 108) talk tail-recursive functions:
note when value returned recursive call returned, in preceding definition
factorial
, function tail-recursive.
but case here? last call in function *
call, won't stack frame preserved (if don't take compiler optimization account)? tail-recursive?
no, it's not tail-recursive. result being returned factorial(n-1)
still has multiplied n
, requires factorial(n)
regain control (thus mandating call factorial(n-1)
call rather jump).
with said, if tail-recursive, compiler still might not tco on it. depends on compiler , optimizations ask do.
Comments
Post a Comment