2015-09-04 80 views
2

有人可以告诉我在输出语句“之前x的值是8”之后流程是如何进行的吗?试图理解一些简单的递归C代码

#include<stdio.h> 

void sum(int x) 
{ 
    if(x==9) 
      return; 

     printf("\n value of x before is %d",x); 

    /* recursive calling of Sum() function */ 

     sum(x+1); 

     printf("\nvalue of x after is %d",x); 
} 

int main() 
{  
    sum(2); 
} 

输出:

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 

回答

1

当你有一个递归函数如下递归调用语句被压入堆栈。

因此,sum(x+1)之后的语句是printf(),它被推入堆栈并在您从函数返回时检索。

当你调用sum(2+1)

printf("\nvalue of x after is %d",x);/* x =2 */ 

被压入堆栈。所以最后推将printf()x=8

1

sum(i)每个呼叫通过

print value of x before is i 
call sum(i + 1) 
print value of x after is i 

然后由

print value of x before is i 

print value of x before is i + 1 
call sum(i + 2) 
print value of x after is i + 1 

print value of x after is i 

. . . 

更换,直到我到达值8的帮助下更换打印报表,这是不言自明的。

0

看看这段代码:

#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函数调用在调用者函数的堆栈框架内。但是,这个并不意味着递归调用函数可以访问其调用者的数据。要做到这一点,您必须像使用其他函数调用一样使用指针。