I tested the build at many optimization levels with both gcc 4.8.1 and clang 3.4.190255, without tail call optimization for this type of code.
Any special reason collatz_aux not receiving tail call optimization?
#include <vector> #include <cassert> using namespace std; vector<unsigned> concat(vector<unsigned> v, unsigned n) { v.push_back(n); return v; } vector<unsigned> collatz_aux(unsigned n, vector<unsigned> result) { return n == 1 ? result : n % 2 == 0 ? collatz_aux(n / 2, concat(move(result), n)) : collatz_aux(3 * n + 1, concat(move(result), n)); } vector<unsigned> collatz_vec(unsigned n) { assert(n != 0); return collatz_aux(n, {}); } int main() { return collatz_vec(10).size(); }
c ++ tail-recursion
pepper_chico
source share