0
void factorial(int n)
{

if(n ==0)
return 1;

int value = n*factorial(n-1);
printf("the value is %d", value)
}

assume the input the function is 4.

so the number of the calls made is 5.

i wanted to know each time a function is called, how the stack allocation happens. Is it some thing like below happens

void factorial(4)
{

if(4 == 0)
return 1;

int value = 4*factorial(3)
printf ("the value is %d",value);

}

void factorial(3)
{
if(3 ==0)
return 1;

int value = 3* factorial (2);




}

my question is for each call, the code is generated like the above mentioned in the stack }

}

1
  • printf isn't c#, it is C - needs to be re-tagged? Commented Apr 11, 2011 at 18:42

2 Answers 2

3

No it doesn't generate a code, it uses the same code for each call.

Read here for more information: http://en.wikipedia.org/wiki/Call_stack

So basically there are a stack pointer which points to the highest point in the stack and for each function this pointer is increased on the number of bytes needed for local variables and some system information allocation. And it decreases back after the function call is finished.

Sign up to request clarification or add additional context in comments.

Comments

0

The code that's generated is the one in your original example, and nothing else. The actual values that get passed to it resemble the code you rolled-out, yes. There is a distinction between code and the data it operates on. Your stack will contain your calls and your local variables, but the code that executes will not change.

7 Comments

so how the recursion happens, if the function contains the local vairables and if these variables become the input for the recursion function
The code calls the same function that it's in, not creates a new copy. Think of code as the recipe. To start reading the recipe at the beginning again does not need a new recipe, just a note where you left off reading it.
@Raghav: Recursion happens exactly as you have it in your code. A function which calls itself (hopefully with a terminating condition, of course). The code itself doesn't go on the call stack, just a pointer to where that code lives in memory. So each item added to the stack during the recursion points to the same location for the executable code.
I guess what the OP's really worried about is tail call optimization.
@yan: Reminds me of the recipe for yogurt, the first ingredient of which is yogurt :)
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.