Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Problem in understanding Recursion....

Status
Not open for further replies.

isaisa

Programmer
May 14, 2002
97
IN
Hi,

I am a beginner in 'C' programming. I faced one problem in understanding the following code.

Here is a code:-

int main()
{
int x,y;

x = recsum(1);
y = recsum(1);
printf("\n x = %d y =%d",x,y);
}

recsum(i)
int i;
{
static int sum =0;
if(i == 3)
return(sum);
else
{
sum += 10;
i++;
recsum(i);
}
}

output:-
x = 20 y =40

Here is the confussion for me. What i think in this case is that i am creating three copies of recsum function[ for i =1, i = 2 & i =3]. When the last recsum gets executed, it returns the sum as 20 but it is not getting collected in a function from which the recursive call is made i.e. the case at i=2. So the value should get lost. Similarly the function copy for i =1 is not collecting any value. Here all the return values should be lost. And the first call to recsum should return any int value and get assigned to x in the main.
This is what i interpret. I am not getting the correct results as per my interpretations.
So can anyone explain me how function return works and stack cleaning. I am using std. 'C' calling convention here.

Thanks in advance.
Sanjay
 
since sum is static, all nested calls to recsum() will use the same instance of sum - which is probably not what you want ?

Try to remove the 'static'
Also the function should return a value when i != 3 ?
/JOlesen
 
Hi,
Thanks for your reply. I have tried with declaring the sum as auto as int sum = 10;

And what i get is ...
x = 10 y = 10;

I am still not getting.When a function returns without any explicit "return" keyword, what it returns ?????

Thanks again.
Sanjay
 
It will return whatever is present in the AX / EAX (Microsoft / Intel) register - that is : more or less 'random'.
More precisely : The calling function will read the register, expecting the called function to put something meaningful into it.
At least that's what I have always seen.
Your compiler should (ought to) give you a warning about this.
You MUST explicitly return a value from your function.

/JOlesen
 
do it correct !!
#include <stdio.h>
int main()
{
int recs(int);
int a = recs(1);
int b = recs(1);
printf(&quot;a=%d b=%d\n&quot;,a,b);
exit(0);
}
int recs(int x)
{
static int sum; /* do not init a static */
if(x == 3) return(sum);
sum += 10;
return(recs(++x));
} vox clamantis in deserto.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top