递归中关于递归语句后面内容的执行

递归函数中,位于递归调用语句后的语句的执行顺序和各个被调用函数的顺序相反

下面看一个经典的例子:

#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); /* 1 */ 
    if(n<4) 
        up_and_down(n+1); 
    printf("Level %d:n location %p/n",n,&n); /* 2 */ 
 } 

输出结果
Level 1:n location 0240FF48
Level 2:n location 0240FF28
Level 3:n location 0240FF08
Level 4:n location 0240FEE8
Level 4:n location 0240FEE8
Level 3:n location 0240FF08
Level 2:n location 0240FF28
Level 1:n location 0240FF48

首先, main() 使用参数 1 调用了函数 up_and_down() ,于是 up_and_down() 中形式参数 n 的值是 1, 故打印语句 #1 输出了 Level1 。然后,由于 n 的数值小于 4 ,所以 up_and_down() (第 1 级)使用参数 n+1 即数值 2 调用了 up_and_down()( 第 2 级 ). 使得 n 在第 2级调用中被赋值 2, 打印语句 #1 输出的是 Level2 。与之类似,下面的两次调用分别打印出 Level3 和 Level4 。

 当开始执行第 4 级调用时, n 的值是 4 ,因此 if 语句的条件不满足。这时候不再继续调用 up_and_down() 函数。第 4 级调用接着执行打印语句 #2 ,即输出 Level4 ,因为 n 的值是 4 。现在函数需要执行 return 语句,此时第 4 级调用结束,把控制权返回给该函数的调用函数,也就是第 3 级调用函数。第 3 级调用函数中前一个执行过的语句是在 if 语句中进行第 4 级调用。因此,它继续执行其后继代码,即执行打印语句 #2 ,这将会输出 Level3 .当第 3 级调用结束后,第 2 级调用函数开始继续执行,即输出Level2 .依次类推.

原文地址:https://www.cnblogs.com/yfz1552800131/p/5349678.html