I am reading on tail recursion as below
Tail recursion refers to a recursive call at the last line. Tail
recursion can be mechanically eliminated by enclosing the body in a
while loop and replacing the recursive call with one assignment per
function argument.
For example
void print(Iterator start, Iterator end, ostream& out=cout) {
if(start == end)
return;
out << *start++ << endl;
print(start, end, out);
}
is converted to iterative by above specification as
void print(Iterator start, Iterator end, ostream& out=cout) {
while(true) {
if(start == end)
return;
out << *start++ << endl;
}
}
In above passage it is mentioned that “replacing recursive call with one assignment per function argument, but in given example we didn’t have any assignment?
Can any one explain and provide example for above explanation about how to translate recursive to iterative function?
The general conversion of recursive to iterative would look like this.
Original code:
Converted code:
The three assignments as in the explanation are included. Assignment (1) is embedded in the
start++, assignments (2) and (3) are optimized away.