C语言容许函数调用它本身,这种调用的过程称为“递归(recursion)”函数
举例说明,以下代码:spa
#include <stdio.h> void up_and_down(int); int main(void) { up_and_down(1); return 0; } void up_and_down(int n) { printf("Level %d: n location %p\n",n,&n); if (n < 3) up_and_down(n+1); printf("LEVEL %d: n location %p\n",n,&n); }
定义一个函数up_and_down(int n),且函数当中再次调用自己。下面是程序运行效果:3d
[root@MiWiFi-R4-srv C]# cc recur.ccode
[root@MiWiFi-R4-srv C]# ./a.out
Level 1: n location 0x7ffdbc113dac
Level 2: n location 0x7ffdbc113d8c
Level 3: n location 0x7ffdbc113d6c
LEVEL 3: n location 0x7ffdbc113d6c
LEVEL 2: n location 0x7ffdbc113d8c
LEVEL 1: n location 0x7ffdbc113dacblog
代码分析;函数up_and_down(int n)中在包含if语句,符合条件变再次调用自身,那么可将up_and_down(int n)分解写成以下形式:递归
void up_and_down(int n) //根据主函数赋值,n=1; {
printf("Level %d: n location %p\n",n,&n);
//输出显示:Level 1 :n ............. if (n < 3) //断定n=1,且小于3;则进入if语句。 { n = n + 1; //在if语句中,n被从新赋值,且值为2。 printf("Level %d: n location %p\n",n,&n);
//输出显示:Level 2 :n ............. if (n < 3) //再次遇到if语句,n等于2,条件语句为真,则执行if语句。 { n = n + 1; //n被从新赋值,且值为3。 printf("Level %d: n location %p\n",n,&n);
//输出显示:Level 3 :n ........... if(n < 3) //执行断定语句,条件语句为假,则跳过if语句。 up_and_down(n+1); printf("LEVEL %d: n location %p\n",n,&n); //执行语句,输出显示:LEVEL 3 :n ......... } printf("LEVEL %d: n location %p\n",n,&n); //执行语句,输出显示:LEVEL 2 :n ............ } printf("LEVEL %d: n location %p\n",n,&n); //执行语句,输出显示:LEVEL 1 :n ........ }
分析代码行为以下。io
1;n 接收到主函数值为1,运行printf()函数,以后断定if语句,条件为真则继续调用自己,执行printf()函数,断定if语句。直到if条件为假,中止调用自己。class
2;当 n 的值为3 时。if条件语句为假,则跳过if语句,执行printf("LEVEL %d: n location %p\n", n , &n);(注意:此时n的值为3).程序
3;当递归函数(n值为3时)执行结束,则将控制权返回给上一级递归(n的值为2)的时候,继续完成递归函数。重复行为,直到返回到主函数,即n的值为1的时候。db