Why isn't g++ tail call optimizing while gcc is?

前端 未结 3 1505
忘掉有多难
忘掉有多难 2020-12-31 15:36

I wanted to check whether g++ supports tail calling so I wrote this simple program to check it: http://ideone.com/hnXHv

using namespace std;

size_t st;

v         


        
3条回答
  •  情歌与酒
    2020-12-31 16:18

    Because you're passing a temporary std::string object to the PrintStackTop(std::string) function. This object is allocated on the stack and thus prevent the tail call optimization.

    I modified your code:

    void PrintStackTopStr(char const*const type)
    {
        int stack_top;
        if(st == 0) st = (size_t) &stack_top;
        cout << "In " << type << " call version, the stack top is: " << (st - (size_t) &stack_top) << endl;
    }
    
    int RealTailCallFactorial(int n, int a = 1)
    {
        PrintStackTopStr("tail");
        if(n < 2)
            return a;
        return RealTailCallFactorial(n - 1, n * a);
    }
    

    Compile with: g++ -O2 -fno-exceptions -o tailcall tailcall.cpp

    And it now uses the tail call optimisation. You can see it in action if you use the -S flag to produce the assembly:

    L39:
            imull   %ebx, %esi
            subl    $1, %ebx
    L38:
            movl    $LC2, (%esp)
            call    __Z16PrintStackTopStrPKc
            cmpl    $1, %ebx
            jg      L39
    

    You see the recursive call inlined as a loop (jg L39).

提交回复
热议问题