I really can’t understand this code. When a function calls itself what really happens? It is related to the concept of stack, I know, but still I can’t solve these questions.
#include<stdio.h>
fun(int);
main()
{
int x=3;
fun(x);
}
fun(int a)
{
if(a<0)
{
fun(--a); // what happens when function calls itself
printf("%d",a);
fun(--a);
}
}
Please explain the sequence of events which occur during this.
Functions are merely code that resides somewhere in memory. Whenever you make a function call, the compiler translates that into an assembly code command for the platform that saves the address of the next command to be executed after the function call is complete as well as tell the processor where to literally “jump” in memory in order to read the next command to be executed.
Recursion works because you can easily tell the processor to “jump” back to the beginning of the function’s code block in memory. The current function that you are calling from has a memory address just like any other function, and therefore there is no difference for the processor to jump to the beginning of the current function’s code block in memory, or some other function’s code block in memory.
The stack comes into play due to the fact that we need to save the return address for the command to execute after we complete the function call, as well as a location to store the current function’s arguments and automatic variables. So as you make successive function calls, there is a call-stack that is created, with arguments as well as return addresses for any previously called functions higher-up on the stack if the stack is growing downwards. This is collectively called the “stack frame” for the function. When you return from a function, the current function’s stack frame is popped off the bottom of the stack, and then the memory address for where the processor needs to jump back to after the function is complete is read and executed. In the case of recursion, this means that we simply jump back to a previous version of the same function, but in this case the automatic stack variables and arguments will be different after we return since we have returned back to a stack frame for a previous version of the function.