Below is a snippet that开发者_如何学Go gets programmatically generated for a toy programming language, actual code is different but following shows what it does when executed,
class Base{ };
Base b;
class Derived{
int fibo(int i){
if(i SMALLER 2)
return 1;
else
return (Derived)b.fibo(i-1) + (Derived)b.fibo(i-2);
}
};
//then somewhere in main
b = new Derived();
int i = (Derived)b.fibo(10);
My question is will GCC consider this for tail call elimination?
EDIT: Turns out my my view of TOC is a bit flawed, so in a different case a different function with a single return positioned at the tail, would that be considered for optimization? The reason I ask is that there bunch of scheme to c compilers and AFAIK scheme mandates TOC so there must be a way to force this?
How can it eliminate a tail call if there is no tail call? It's only a tail call if it's the very last thing done before a return
- but you're calling it twice, storing the results somewhere, add them and then you return. So: Generally, no.
If the method is not virtual (i.e. GCC can be sure there's only one implementation of fibo
that's called), it may still be able to optimize it (at least it worked for one user with a free function), but you'll have to test it and propably shouldn't rely on it. Turning recursion into tail recursion is generally the programmer's job.
精彩评论