Stack function call issue

i has a function called fun1() , which is used for recursion. I am confused about the first call to this fun(--n); . What will it do, and how will my stack perform my functions after each function completes?

 void fun(int n) { if(n>0) { fun(--n); printf("%d",n); fun(--n); } } 

My main function is as follows:

  int a; a=3; fun(a); 

I want to know the execution order and what my stack will contain before, during and after the function call of the first fun(--n) .

+6
source share
4 answers

Your output will be 0, then 1, then 2, and then 0.

  • Initially called with 3
  • More than 0, it calls fun (-n), which makes it 2.
  • This continues until it reaches 0.
  • It continues to printf () and prints 0 to the console.

What you do not see are intermediate calls. This is the full conclusion (to 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 
+3
source

He 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 a call tree. Read the following: the first number in ( ) , wrapped in { } , is the value that the function receives for one call, the next number following the arrow is the value reduced by one, and it is used to call back. On return, [ ] returned. The last number in ( ) is the value that is used for the second call after printf . (X) means that it cannot get into the if block. At the end of each bracket ( ) function returns to the point from where it was created (follow the lines). Note that the value is returned after the return of the first call.

+7
source

Well, every time you create prerequisites, you decrease the value of n by one. The function call will go down to the very bottom before something is printed, then one of the most recent printfs will be called, etc. You can visualize downstream calls as follows:

 fun(5): * P fun(4): * P fun(3): * P * P fun(2): * PP * P * PP fun(1): *P *P *P *P *P time -->->-> 

where P is a printout and * a new call (maybe it could be some typos). If you did not decrement a second time, you get a W-look call schedule, as it continues to decline again and again, but the second set of calls to each function is on the β€œcone” below, so it looks crushed on the right. Stack no more than 5 depths (if the first call was funny (5), say).

I don't know if this visualization helps, but I did my best with ASCII.

+4
source

It should look something like this:

at the beginning: fun (3) first call: fun (2) at the end: fun (1)

-2
source

Source: https://habr.com/ru/post/896507/


All Articles