void
binary_to_ascii( unsigned int value )
{
unsigned int quotient;
quotient = value / 10;
if( quotient != 0)
binary_to_ascii( quotient );
putchar(value % 10 + '0' );
}
程序的目的是把一个整数从二进制形式转换为可打印的字符形式。例如426,我们需要一次产生字符‘4’,‘2’,‘6’。
通过这个程序可以很好的说明C的递归是依靠运行时的堆栈支持的。追踪一个递归函数的执行过程的关键是理解函数中所声明的变量是如何存储的。当函数被调用时,它的变量的空间是穿件于运行时的堆栈上的。以前调用的函数的变量仍保留在堆栈加上,但它们被新函数的变量所掩盖,因此是不能被访问的。
下面将演示实例程序的变量存储过程(二维表表示堆栈,第一行表示栈顶):
程序中有两个变量: value,quotient。
value=426 | quotient= |
其他函数调用使用的变量 | 其他函数调用使用的变量 |
value=426 | quotient=42 |
其他函数调用使用的变量 | 其他函数调用使用的变量 |
value=42 | quotient= |
value=426 | quotient=42 |
其他函数调用使用的变量 | 其他函数调用使用的变量 |
value=42 | quotient=4 |
value=426 | quotient=42 |
其他函数调用使用的变量 | 其他函数调用使用的变量 |
value=4 | quotient=0 |
value=42 | quotient=4 |
value=426 | quotient=42 |
其他函数调用使用的变量 | 其他函数调用使用的变量 |
quotient=0时,递归函数将不再调用自己,而是开始打印输出。
value=4 | quotient=0 |
value=42 | quotient=4 |
value=426 | quotient=42 |
其他函数调用使用的变量 | 其他函数调用使用的变量 |
接着函数返回,它的变量从堆栈中销毁。接着,递归函数的前一次调用重新继续执行,它所使用的是自己的变量,它们现在位于堆栈的顶部。因为它的value值是42,所以调用putchar后打印出来的数字是2。
value=42 | quotient=4 |
value=426 | quotient=42 |
其他函数调用使用的变量 | 其他函数调用使用的变量 |
value=426 | quotient=42 |
其他函数调用使用的变量 | 其他函数调用使用的变量 |
然后,这个递归函数就彻底返回到其他函数调用它的地点。