Consider the following code:
int fac_aux( int x, int res ) {
if( x == 1 ) return res;
else return fac_aux( x - 1, res * x );
}
int fac( int x ) {
return fac_aux( x, 1 );
}
int main() {
int x = fac( 50 );
std::cout << x;
return 0;
}
According to generated asm file everything is ok, tail call is optimized.
Try to replace
int x = fac( 50 );
with
int x = fac_aux( 50, 1 );
Strange enough, but tail call optimization is disappeared. As far as I remember there was no such a strange compiler behaviour in VS2008. Any ideas why these things happen and how to be sure of tail call optimization is done?
; Function compile flags: /Ogtp
Tried both /O2 and /Ox optimization flags. Are there any other compiler options that matter?
Edit: VS2012 manages to do the optimization
Try making the functions explicitly
inline
– furthermore, what optimization level are you using?I tried the following code
and used the full optimization /Ox but I did not get the tail recursion. So it seems that MS VC++ 2010 does not support the tail recursion.
I don't know if it will work, but try to replace if ... else with single return statement:
Looks weird, are you doing some kind of incremental compile. Other than that, it might be the fact that compiler gets confused by the multiple parameters, in the working version there's effectively only one parameter, somehow the optimization doesn't qualify anymore.
You could try making the res parameter a global, I its know messy bad practice, but it might work.
Sounds like a compiler bug/feature.
/Tony
when the original is compiled, the assembly at the callsite has partial inlining of
fac_aux
, specifically thex - 1
part, which is required for the tail recursion, but usingfac_aux
prevents the partial inlining and thus the tail recursion optimization: