確定是否發生尾呼叫的一種方法是查看是否可以強制堆棧溢出。採用VC++ 2005 Express Edition的下列程序不產生堆棧溢出,並,即使其結果相當迅速地超過長一倍的容量,你可以告訴所有的迭代正在處理時,TCO正在發生的事情:
/* FibTail.c 0.00 UTF-8 dh:2008-11-23
* --|----1----|----2----|----3----|----4----|----5----|----6----|----*
*
* Demonstrate Fibonacci computation by tail call to see whether it is
* is eliminated through compiler optimization.
*/
#include <stdio.h>
long double fibcycle(long double f0, long double f1, unsigned i)
{ /* accumulate successive fib(n-i) values by tail calls */
if (i == 0) return f1;
return fibcycle(f1, f0+f1, --i);
}
long double fib(unsigned n)
{ /* the basic fib(n) setup and return. */
return fibcycle(1.0, 0.0, n);
}
int main(int argc, char* argv[ ])
{ /* compute some fibs until something breaks */
int i;
printf("\n i fib(i)\n\n");
for (i = 1; i > 0; i+=i)
{ /* Do for powers of 2 until i flips negative
or stack overflow, whichever comes first */
printf("%12d %30.20LG \n", i, fib((unsigned) i));
}
printf("\n\n");
return 0;
}
但是請注意,該簡化,以使fibcycle純尾調用無異於搞清楚一個交互的版本,根本不會做尾調用(並有或無TCO的編譯器工作。
這可能是有趣的,以看TCO如何會發現,是不是已經接近最佳,並通過迭代容易更換的優化實驗。