看看这段代码:
#include<stdio.h>
void p(int x) {
while(x--) putchar(' ');
}
void sum(int x)
{
if(x==9)
return;
p(x); printf("value of x before is %d\n",x);
/* recursive calling of Sum() function */
sum(x+1);
p(x); printf("value of x after is %d\n",x);
}
int main()
{
sum(2);
}
将输出这样的:
$ ./rec
value of x before is 2
value of x before is 3
value of x before is 4
value of x before is 5
value of x before is 6
value of x before is 7
value of x before is 8
value of x after is 8
value of x after is 7
value of x after is 6
value of x after is 5
value of x after is 4
value of x after is 3
value of x after is 2
这意味着该函数调用的行为就像如下:
sum(2)
2 is 2 == 9? NO
2 print before
2 sum(3)
2 3 is 3 == 9? NO
2 3 print before
2 3 sum(4)
2 3 4 is 4 == 9? NO
2 3 4 print before
2 3 4 sum(5)
2 3 4 5 is 5 == 9? NO
2 3 4 5 print before
2 3 4 5 sum(6)
2 3 4 5 6 is 6 == 9 ? NO
2 3 4 5 6 print before
2 3 4 5 6 sum(7)
2 3 4 5 6 7 is 7 == 9 ? NO
2 3 4 5 6 7 print before
2 3 4 5 6 7 sum(8)
2 3 4 5 6 7 8 is 8 == 9 NO
2 3 4 5 6 7 8 print before
2 3 4 5 6 7 8 sum(9)
2 3 4 5 6 7 8 9 is 9 == 9? YES
2 3 4 5 6 7 8 9 RETURN
2 3 4 5 6 7 print after
2 3 4 5 6 7 RETURN
2 3 4 5 6 print after
2 3 4 5 6 RETURN
2 3 4 5 print after
2 3 4 5 RETURN
2 3 4 print after
2 3 4 RETURN
2 3 print after
2 3 RETURN
2 print after
2 RETURN
main continues here
领先数字表示“哪个”sum()
函数。这是该函数中的x
的值。
此外,注意与值3的功能是“内部”用值2和功能值4是“内部”与价值函数功能3.
我说,因为里面随后的stack frames函数调用在调用者函数的堆栈框架内。但是,这个并不意味着递归调用函数可以访问其调用者的数据。要做到这一点,您必须像使用其他函数调用一样使用指针。