stack function call problem
i have a function called fun1()
, which is used for recursion. I am confused regarding the first call to this fun(--n);
. What it will do and how will my stack pop my functions after each function finishes?
void fun(int n)
{
if(n>0)
{
开发者_Go百科fun(--n);
printf("%d",n);
fun(--n);
}
}
My main function is as below:
int a;
a=3;
fun(a);
I want to know the order of execution and what my stack will contain before, during, and after the function call of the first fun(--n)
.
It will print 0120
(3->[2]->1)
+ +
| |
+------------+ +-------+
| |
({2}->[1]->0) ({1}->[0]->-1)
+ + +
| | |
+--------------+ +----+ |
| | +
| | (X)
+ +
({1}->[0]->-1) (0->X)
+ +
| |
+------------+ |
| |
| |
+ +
({0}->X) (X)
The above is a representation of the call tree. Read like this: The first number in the ( )
, wrapped in { }
is the value which the function receives for one call, the next number following an arrow represents the value decreased by one and it is used to call again. The [ ]
represents when returning it is printed. The last number in ( )
is the value which is used to the second call after the printf
. An (X)
represents that it is not able to get into the if
block. At the end of each ( )
braces the function returns to the point where it originated from (follow the lines). Note the value gets printed after returning of the first call.
Well, each time you predecremement, you will reduce the value of n
by one. The function calls will descend all the way to the bottom before anything is printed, then one of the bottom-most printfs will be called, and so on. You might like to visualise the descending calls like this:
fun(5): * P
fun(4): * P
fun(3): * P * P
fun(2): * P P * P * P P
fun(1): *P *P *P *P *P
time -->->->
where P represents a print and * a new call (might well be some typos in there). If you weren't doing the decrementing a second time, you get a W-looking call graph, as it keeps going down and up again and down, but the second set of calls of each function is on 'cone' lower, so it looks squashed on the right. The stack is never more than 5 deep (if the first call was fun(5), say).
No idea if that visualisation helps, but I did my best with the ASCII.
Your output will be 0, then 1, then 2, and then 0.
- Initially called with 3
- Greater than 0, it calls fun(--n), which makes it 2.
- This continues until it reaches 0.
- It continues to the printf(), and prints 0 to the console.
What you aren't seeing is the intermediate calls. This is the full output (before the n > 0 part):
Fun call before n > 0; n = 3
Fun call before n > 0; n = 2
Fun call before n > 0; n = 1
Fun call before n > 0; n = 0
0
Fun call before n > 0; n = -1
1
Fun call before n > 0; n = 0
2
Fun call before n > 0; n = 1
Fun call before n > 0; n = 0
0
Fun call before n > 0; n = -1
Should look something like this:
at start: fun(3) first call: fun(2) at end: fun(1)
精彩评论