If bar calls bar(i/2) if i is an even integer and bar(3*i + 1) otherwise, the recursive function bar would tail-recursion.
const int bar(const int i)
{
if (i < 2) return i;
return i % 2 ? bar(i/2) : bar(3*i + 1);
}
However, what if bar calls either bar or foo, who has a completely different set of local variables from bar?
const int bar(const int i)
{
if (i < 2) return i;
return i % 2 ? bar(i/2) : foo(3*i + 1);
// where foo is very complicated recursive call that has
// 11 different user-defined/primitive type of
// local variables that can't be optimized out
}
My understanding is tail recursion optimization will use caller's stack. The caller is already done with its local variables before calling the callee. So, the callee can reuse it. My understanding sounds fine when the caller and callee are the same function(e.g. foo calls foo, bar calls bar). However, if the stack size and layout are totally different, and the callees might be one of multiple different functions with different stack layout, what is going to happen?
Firstly, would it be tail recursion? (Now, I understand that tail "call" optimization might be applied to but not this is not tail "recursion.") Secondly, major compilers such as gcc, clang, etc, would optimize this kind of tail calls? (The answer seems yes.)
What if the callee (foo in the second code example) is much more complicated? If the callee and caller are calling each other (mutual recursion), is the call in my second code example would be tail-call-optimized? If the callee (e.g. foo) is a complicated recursive call that is definitely not a tail recursion and very hard for a compiler to reduce it to a loop or so, would it be still tail-call-optimized?
foo()frombar()is not recursion. So I fail to see the relevance. - Disillusionedfoo()is not a substitute for demonstration.) So: What's your point? OP doesn't demonstrate any kind of recursion withfoo(). So I still don't see the relevance. - Disillusioned