考虑 C 中的尾递归阶乘实现:
#include <stdio.h>
unsigned long long factorial(unsigned long long fact_so_far, unsigned long long count, unsigned long long max_count){
if (max_count==0 || max_count==1 || count >= max_count)
return fact_so_far;
else
{
printf("%llu %p \n", count, &factorial);
return factorial(fact_so_far * count, ++count, max_count);
}
}
int main(int argc, char **argv)
{
unsigned long long n;
scanf("%llu", &n);
printf("\n Factorial %llu \n",factorial(1,0,n));
return 0;
}
我在“阶乘”中放置了一个断点,然后在“gdb”下运行上面的代码。断点永远不会被击中。
假设它的尾调用已优化(我已使用 gcc -O2 对其进行编译),它应该至少命中一次断点,IIRC。
编辑:我得到最终结果而没有遇到任何断点。例如,
(gdb) b factorial
Breakpoint 1 at 0x8048429: file factorial-tail.c, line 3.
(gdb) run
Starting program: /home/amit/quest/codes/factorial-tail
5
0 0x8048420
1 0x8048420
2 0x8048420
3 0x8048420
4 0x8048420
Factorial 120
Program exited normally.
(gdb)
我哪里错了?