Reputation: 31
In C++ can I use a table of function pointers to jump (not call) a function? I know how to make and call a jump table, but I am building a scanner and want to jump between routines efficiently, so I want to do a jump so the same stack frame is used for the target routine. I will make the profiles the same.
Upvotes: 3
Views: 141
Reputation: 283694
No you can't, but there is a well-known pattern to avoid accumulation of stack frames during repeated lookups: Continuation-Trampoline Style.
Instead of this:
void scanner1( ... )
{
fn_table[next]();
}
do this:
int scanner2( ... )
{
return next;
}
while ((next = fn_table[next]()) != END) {}
Because there's a return immediately preceding every call, the stack depth doesn't increase.
An additional benefit is that if you want to add tracing of the states visited, you can do so at a single point (inside the trampoline-processing loop) instead of scattered across all scanner functions.
It gets more complicated if there's state to pass to the next handler, but not by very much (use output params instead of return value, for example, or return a smart pointer to a functor object, e.g. std::function<void()>
that has the arguments prebound).
This is also covered in the wikipedia article on tail recursion.
Upvotes: 8