Click here to Skip to main content
15,891,136 members
Please Sign up or sign in to vote.
3.00/5 (1 vote)
See more:
[
C#
#include <stdio.h>
#include <stdlib.h>

int main()
{
    static int i=5;
    if(--i)
    {
    main();
    printf("%d\n",i);
    }
    return 0;
}

]
Posted

What you have is head recursion. See The difference between head & tail recursion[^]. As long as the static variable i is not zero, the recursion takes place (4 times). While unwinding the recursion (in the tail of each recursive call), the current value of the static variable is printed. If it was a local variable instead of a static variable, the result was different --> a stack overflow since the stop condition for the recursion was never met.
Cheers
Andi
 
Share this answer
 
Comments
Anupkumar_vj 24-Dec-15 12:58pm    
I have gone through your give link. Still I didn't get unwinding the recursion the current value of static variable.
Andreas Gieriet 24-Dec-15 15:44pm    
Go ahead and write the recursion down on paper. That's the only way to learn how it works.
Make a column for the static variable and one column of each level of recursion of the main function. Write down the value of i from the beginning to the end of the recursion and write down in the respective value plus in the recursion row the current statement of execution.
This will teach you the machinery of recursion.
E.g.
level 0: i=5 static int i = 5;
level 0: i=4 if (--i)
level 0: i=4 main()
level 1: i=3 if (--i)
level 1: i=3 main()
level 2: i=2 if (--i)
level 2: i=2 main()
level 3: i=1 if (--i)
level 3: i=1 main()
level 4: i=0 if (--i)
level 4: i=0 return 0
level 3: i=0 printf(0)
level 3: i=0 return 0
level 2: i=0 printf(0)
level 2: i=0 return 0
level 1: i=0 printf(0)
level 1: i=0 return 0
level 0: i=0 printf(0)
level 0: i=0 return 0
Cheers
Andi
This happens because, when it comes to "printf", the value of a output variable "i" became zero.
You can put "printf" before "main".
More better to write recursion like this:

C++
void recuot(int n)
{
	if (n > 1)
		recuot(n-1);
	printf("%d\n",n);;
}
int main()
{
	recuot(5);
	return 0;
}
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900