Tail call optimization

Aug 04, 2025

I have always accepted the fact that a recursive implementation can be easily optimized by the compiler if the recursive call is in the tail position, but I never understood why. That can be easily understood in C if we reimplement a recursive function using goto. For example, let’s implement a recursive function that counts the number of numbers between two numbers:

int count(int start, int end, int n) {
    if (start > end) return n;
    return count(start + 1, end, n + 1);
}

Refactoring that to use goto, we can see that by having a recursive count call as the last action, it’s easy to optimize to keep the same stack frame while transitioning the state across iterations.

int count(int start, int end, int n) {
iterate:
    if (start > end) return n;
    start = start + 1;
    n = n + 1;
    goto iterate;
}

#tail call optimization