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

前端 未结 5 825
再見小時候
再見小時候 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:45

    All current mainstream compilers perform tail call optimisation fairly well (and have done for more than a decade), even for mutually recursive calls such as:

    int bar(int, int);
    
    int foo(int n, int acc) {
        return (n == 0) ? acc : bar(n - 1, acc + 2);
    }
    
    int bar(int n, int acc) {
        return (n == 0) ? acc : foo(n - 1, acc + 1);
    }
    

    Letting the compiler do the optimisation is straightforward: Just switch on optimisation for speed:

    • For MSVC, use /O2 or /Ox.
    • For GCC, Clang and ICC, use -O3

    An easy way to check if the compiler did the optimisation is to perform a call that would otherwise result in a stack overflow — or looking at the assembly output.

    As an interesting historical note, tail call optimisation for C was added to the GCC in the course of a diploma thesis by Mark Probst. The thesis describes some interesting caveats in the implementation. It's worth reading.

提交回复
热议问题