Thread: recursion and stack - trying to understand

  1. #1
    Registered User
    Join Date
    Jan 2011
    Posts
    144

    recursion and stack - trying to understand

    Hi all,
    I am trying to understand what goes on in stack with the following code. Once its hit the base case (n == 1), how does it start unwinding?

    I have the following picture attached.
    http://i41.tinypic.com/21m4t90.png

    1. 1 is returned to fact(n-1) where n is 2. Therefore, val = 2 * 1
    2. Now that val is 2, is this returned to fact(2)?

    Code:
    #include <stdio.h>
    
    int fact(int n)
    {
    	int val;
    
    	if (n == 1)
    		return 1;
    	else 
    		val = n * fact(n-1);	//b
    
    	return val;
    
    }
    
    int main()
    {
    	printf("%d", fact(3));	//a
    
    	getchar();
    	return 0;
    }

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,666
    So why not change the code and add some prints
    Code:
    int fact(int n)
    {
        int val;
     
        printf("Called with n=%d\n", n);
        if (n == 1)
            val = 1;
        else
            val = n * fact(n-1);    //b
     
        printf("returning from fact(%d) with result=%d\n", n,val);
        return val;
     
    }
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  3. #3
    Registered User
    Join Date
    Jun 2005
    Posts
    6,815
    The call stack is built by main() calling fact(3) which results in fact(2) being called which results in fact(1) being called. When the inner most call of fact (called as fact(1)) returns, it returns 1. That 1 is multiplied by 2, to return a result of 2 (fact(2)). That value is multiplied by 3, to return a result of 6 (fact(3)). That is the value which gets returned to main(), in the printf() statement, so the value of 5 is returned.

    As to what goes on the stack .... whatever is necessary to ensure that sequence of events happens. Generally that will include values of function argument (e.g. main() calling fact(3) will result in a value of 3 on the stack, so it can be retrieved as n inside the fact() function) and tracking call context (so, for example, the deepest call of fact() returns the value of 1 to the call of fact that is calculating fact(2), rather than directly to main()).

    The variables and values used by the functions are also usually copied to the stack as well. So, when fact(1) is being executed, there is a val corresponding to it (never used) and and an n (with value 1). However, there is an active call of fact(2) active which called fact(1), and it has its own local version of n and val. Similarly for the call of fact() with argument of 3.

    The specifics are highly compiler dependent. Depending on how smart it is, the compiler may eliminate unnecessary variables (it is trivial to rewrite your function so it produces the same result without using the variable val at all, but gives the same result). It may also turn your fact() function into a loop - with no recursion whatsoever - since it is essentially tail-recursive (i.e. the last significant operation it does before returning is call itself, and it is guaranteed that every such call will eventually return). If the compiler does such things, it might eliminate the need for anything on the stack, other than what is needed in main() to call fact(3). And a really smart compiler or linker might even inline the call of fact() completely, and simply print out the value of 6.
    Right 98% of the time, and don't care about the other 3%.

    If I seem grumpy or unhelpful in reply to you, or tell you you need to demonstrate more effort before you can expect help, it is likely you deserve it. Suck it up, Buttercup, and read this, this, and this before posting again.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 2
    Last Post: 04-08-2012, 10:32 AM
  2. Stack overflow in recursion
    By Nom1fan in forum C Programming
    Replies: 4
    Last Post: 11-24-2010, 12:51 PM
  3. Callback recursion: stack overflow
    By nicoqwertyu in forum C++ Programming
    Replies: 8
    Last Post: 03-16-2010, 11:09 AM
  4. help me understand the stack
    By bling in forum C++ Programming
    Replies: 10
    Last Post: 08-26-2008, 06:08 AM
  5. stack and recursion help needed!
    By LouB in forum C++ Programming
    Replies: 3
    Last Post: 07-01-2002, 02:19 PM