Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can this be tail call optimized? If so, what's the special reason for it not happen?

I've checked assembly output at many optimization levels with both gcc 4.8.1 and clang 3.4.190255, no tail call optimization for this kind of code.

Any special reason why collatz_aux doesn't get a 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();
}
like image 802
pepper_chico Avatar asked Sep 25 '13 14:09

pepper_chico


1 Answers

The destructor for the vector<unsigned> parameter needs to be called after the return.

like image 185
Simple Avatar answered Sep 24 '22 15:09

Simple