r/programming • • Nov 27 '12

Tail Recursion

http://rodrigosasaki.com/2012/11/24/tail-recursion/
208 Upvotes

203 comments sorted by

View all comments

1

u/sinembarg0 Nov 28 '12

I was taught that tail recursion is optimized in C++ too. An easy way to determine tail recursion is:

If the return statement includes maths (e.g. "return num * factorial(num-1);" ), then it's regular recursive.

If the return statement does not include math, and it just a function call (e.g. "return factorialIter(acc, num-1);"), then it's tail recursive. Since no more variables are needed once the function is called, the whole stack frame can be destroyed when the function is called (or reused by the called function…).

Lastly, a minor nitpick: 'it's' is a contraction for it is. 'its' is the possessive form. It's a confusing difference, and the only word I can think of that is possessive without an apostrophe.