struct fib_state
{
void* ret_addr;
int n;
int n_minus_1;
int n_minus_2;
int ret_val;
};
std::stack<fib_state> stack;
void* call(void* func_addr, int n, void* ret_addr)
{
stack.push(fib_state{ ret_addr, n });
return func_addr;
}
void* ret(int ret_val)
{
void* p =
stack.top().ret_addr;
stack.pop();
stack.top().ret_val = ret_val;
return p;
}
int fib(int n)
{
stack.push(fib_state{});
goto* call(&& fib_func, n, && ret);
ret:
return
stack.top().ret_val;
fib_func:
if (
stack.top().n <= 2)
{
goto* ret(1);
}
{
goto* call(&& fib_func,
stack.top().n - 1, && lbl_1);
lbl_1:
stack.top().n_minus_1 =
stack.top().ret_val;
}
{
goto* call(&& fib_func,
stack.top().n - 2, && lbl_2);
lbl_2:
stack.top().n_minus_2 =
stack.top().ret_val;
}
goto* ret(
stack.top().n_minus_1 +
stack.top().n_minus_2);
}
简单、粗暴、有效、好使。
再复杂的递归函数都能 goto 出来……