Which, if any, C++ compilers do tail-recursion optimization?

前端 未结 5 818
再見小時候
再見小時候 2020-11-22 12:45

It seems to me that it would work perfectly well to do tail-recursion optimization in both C and C++, yet while debugging I never seem to see a frame stack that indicates th

5条回答
  •  感动是毒
    2020-11-22 13:43

    gcc 4.3.2 completely inlines this function (crappy/trivial atoi() implementation) into main(). Optimization level is -O1. I notice if I play around with it (even changing it from static to extern, the tail recursion goes away pretty fast, so I wouldn't depend on it for program correctness.

    #include 
    static int atoi(const char *str, int n)
    {
        if (str == 0 || *str == 0)
            return n;
        return atoi(str+1, n*10 + *str-'0');
    }
    int main(int argc, char **argv)
    {
        for (int i = 1; i != argc; ++i)
            printf("%s -> %d\n", argv[i], atoi(argv[i], 0));
        return 0;
    }
    

提交回复
热议问题