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
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