Please explain how the return call from nested recursive function propagates all the way out to main?
I came across the following code segment in a book. The printf output is '6, 12'
In the recursive function sumdig(), a return statement is called in third recursive call.
When sumdig() now returns to the second recursive call, sumdig() should evaluate to an expression, not a return statement (i.e. return sumdig(n)).
But that is not what seems to happen. The return call from the recursive function is being propagated all the way out to main.
Can anyone please explain how the return call from nested recursive function propagates all the way out to main?
The code below would have made sense to me if the recursive call was something like 'return sumdig(n)'.
main()
{
int a, b;
a = sumdig( 123 );
b = sumdig( 123 );
printf( "%d, %d\n", a, b);
}
sumdig(int n)
{
static int s = 0;
int d;
if(n != 0)
{
d = n % 10;
n = (n - d) / 10;
s = s + d;
sumdig(n);
}
else
return(s);
}
Recursive calls for Sumdig
Initial call :n = 123, s = 0
First recursive call :n = 12, s = 3
Second recursive call :n = 1, s = 5
Third recursive call :n = 0, s = 6 // Return statement happens here
Likewise For Second call...the static variable will increment by 6 again to become 12.
If my question is not clear, please help me improve it.