# Tail call optimisation in C++

This series: Lightning talk, Explanation, Performance, Generalisation.

Some programming languages make recursive programming more practical by providing the tail call optimisation. For a tiny talk at the recent ACCU conference I looked at how we might do something similar in C++.

### Multiplying by two

Here’s a toy problem we will use as our example.

Imagine for a second that you want to write a function that multiplies a number by two. OK, we can do that:

```long times_two_hardware( long value )
{
return value * 2;
}```

Now imagine that you don’t have the “*” operator. We’re going have to use “+”:

```long times_two_loop( long value )
{
long ret = 0;
for ( long i = 0; i < value; ++i )
{
ret += 2;
}
return ret;
}```

(Obviously, this is just a silly example designed to be easy to follow.)

Now imagine that you read somewhere that state was bad, and you could always replace a loop with recursion. Then you might get something like this:

```long times_two_naive_recursive( long value )
{
if ( value == 0 )
{
return 0;
}
else
{
return 2 + times_two_naive_recursive( value - 1 );
}
}```

This is fine, but what happens when you run it for a large input?

```\$ ulimit -S -s 16
\$ ./times_two naive_recursive 100000
Segmentation fault```

Note that I set my stack size to be very small (16K) to make the point - actually, this will run successfully for very large arguments, but it will eat all your memory and take a long time to finish.

Why does this fail? Because every time you call a function, the state of the current function is saved, and new information is pushed onto the stack about the new function. When you call a function from within a function multiple times, the stack grows and grows, remembering the state all the way down to the place where you started.

So is programming like this useless in practice?

### Tail call optimisation

No, because in several programming languages, the compiler or interpreter performs the "tail call optimisation".

When you call a function from within some other code, you normally need the state of the current code to be preserved. There is a special case where you don't need it, though, and this is called a tail call. A tail call is just the situation where you call a function and immediately return its return value as your return value. In this case, we don't need any of the state of the current code any more - we are just about to throw it away and return.

The tail call optimisation throws away this unneeded state before calling the new function, instead of after.

[In practice, in compiled code, this involves popping all the local variables off the stack, pushing the new function parameters on, and jmping to the new function, instead of calling it. This means that when we hit the ret at the end of the new function, we return to the original caller, instead of the location of the tail call.]

Many recursive functions can be re-cast as tail-call versions (sometimes called iterative versions). The one we're looking at is one of those. Here is the tail-call version:

```long times_two_recursive_impl( long total, long counter )
{
if ( counter == 0 )
{
}
else
{
return times_two_recursive_impl(
total + 2, counter - 1 );
}
}

long times_two_recursive( long value )
{
return times_two_recursive_impl( 0, value );
}```

It consists of an outer function times_two_recursive which just hands off control to the inner function times_two_recursive_impl. The inner function uses a counter variable and calls itself recursively, reducing that counter by one each time, until it reaches zero, when it returns the total, which is increased by 2 each time.

The key feature of this implementation is that the recursive function times_two_recursive_impl uses a tail call to do the recursion: the value of calling itself is immediately returned, without reference to anything else in the function, even temporary variables.

So, let's see what happens when we compile and run this:

```\$ ulimit -S -s 16
\$ ./times_two recursive 100000
Segmentation fault```

Did I mention that C++ doesn't do the tail call optimisation?*

* Tail call optimisation isn't in the C++ standard. Apparently, some compilers, including MS Visual Studio and GCC, do provide tail call optimisation under certain circumstances (when optimisations are enabled, obviously). It is difficult to implement for all cases, especially in C++ since destruction of objects can cause code to be executed where you might not have expected it, and it doesn't appear to be easy to tell when a compiler will or will not do it without examining the generated assembly language. Languages which have this feature by design, like Scheme (and D?) can do it more predictably.

So how would we write code that is tail call optimised in C++? Possibly of more interest to me personally: if we were generating C++ as the output format for some other language, what code might we generate for tail call optimised functions?

### Tail call optimised C++

Let's imagine for a second we have some classes, which I'll define later. FnPlusArgs holds a function pointer, and some arguments to be passed to it. Answer holds on to one of 2 things: either a FnPlusArgs to call later, or an actual answer (return value) for our function.

Now we can write our function like this:

```Answer times_two_tail_call_impl( long acc, long i )
{
if ( i == 0 )
{
return Answer( true, null_fn_plus_args, acc );
}
else
{
false,
FnPlusArgs(
times_two_tail_call_impl,
acc + 2,
i - 1
),
0
);
}
}

long times_two_tail_call( long n )
{
false,
FnPlusArgs( times_two_tail_call_impl, 0, n ),
0 ) );
}```

This has the same structure as times_two_recursive, if a little more verbose. The important point to note, though, is that times_two_tail_call_impl doesn't call itself recursively. Instead, it returns an Answer object, which is a delegate saying that we have more work to do: calling the provided function with the supplied arguments.

### The Trampoline

All we need now is some infrastructure to call this function, and deal with its return value, calling functions repeatedly until we have an answer. This function is called a "trampoline", and you can sort of see why:

```long trampoline( Answer answer )
{
{
}
}```

While the answer we get back tells us we have more work to do, we call functions, and when we're finished we return the answer.

Now all we need to get this working is the definition of Answer and FnPlusArgs:

```struct Answer;
typedef Answer (*impl_fn_type)( long, long );

struct FnPlusArgs
{
impl_fn_type fn_;
long arg1_;
long arg2_;

FnPlusArgs(
impl_fn_type fn,
long arg1,
long arg2
);

};

impl_fn_type null_fn = NULL;
FnPlusArgs null_fn_plus_args( null_fn, 0, 0 );

{
bool finished_;
FnPlusArgs tail_call_;
long value_;

Answer( bool finished, FnPlusArgs tail_call, long value );
};

FnPlusArgs::FnPlusArgs(
impl_fn_type fn,
long arg1,
long arg2
)
: fn_( fn )
, arg1_( arg1 )
, arg2_( arg2 )
{
}

{
return fn_( arg1_, arg2_ );
}

: finished_( finished )
, tail_call_( tail_call )
, value_( value )
{
}```

The only notable thing about this is that we use operator() on FnPlusArgs to call the function it holds.

### Results

Now, when we run this code, we get what we wanted:

```\$ ulimit -S -s 16
\$ ./times_two tail_call 100000
200000```

(I.e. it doesn't crash.)

So, it turns out that the tail call optimisation is just a while loop. Sort of.

## 4 thoughts on “Tail call optimisation in C++”

1. Konstantin says:

Function times_two_tail_call( long n ) run tail_call( Answer(… which is not defined in example
I suppose that function trampoline should run instead or corresponding typedef for tail_call as trampoline should be defined

2. Andy Balaam says:

Hi Konstantin, thanks – that’s right – it should be trampoline inside times_two_tail_call. I’ll change it.

This site uses Akismet to reduce spam. Learn how your comment data is processed.