递归函数Recursive Functions

C 程序中的任何函数都可以以递归方式调用;也就是说,函数可以调用自己。Any function in a C program can be called recursively; that is, it can call itself. 递归调用的数量受堆栈的大小的限制。The number of recursive calls is limited to the size of the stack. 有关设置堆栈大小的链接器选项的信息,请参阅 /STACK(堆栈分配)(/STACK) 链接器选项。See the /STACK (Stack Allocations) (/STACK) linker option for information about linker options that set stack size. 每次调用函数时,都会为参数以及 auto 和 register 变量分配新存储,以便不会覆盖它们在前面未完成的调用中的值。Each time the function is called, new storage is allocated for the parameters and for the auto and register variables so that their values in previous, unfinished calls are not overwritten. 只有从中创建参数的函数的实例才能直接访问该参数。Parameters are only directly accessible to the instance of the function in which they are created. 前面的参数对函数的后续实例不可直接访问。Previous parameters are not directly accessible to ensuing instances of the function.

请注意,使用 static 存储声明的变量在每次递归调用时不需要新存储。Note that variables declared with static storage do not require new storage with each recursive call. 它们的存储在程序的生存期内存在。Their storage exists for the lifetime of the program. 每次引用此类变量时都将访问相同的存储区域。Each reference to such a variable accesses the same storage area.

示例Example

本示例演示了递归调用:This example illustrates recursive calls:

int factorial( int num );      /* Function prototype */  

int main()  
{  
    int result, number;  
    .  
    .  
    .  
    result = factorial( number );  
}  

int factorial( int num )      /* Function definition */  
{  
    .  
    .  
    .  
    if ( ( num > 0 ) || ( num <= 10 ) )  
        return( num * factorial( num - 1 ) );  
}  

另请参阅See Also

函数调用Function Calls