Your confusion, I believe, comes from the fact that you think there is only one result
variable, whereas actually there is a result
variable for each function call. Therefor, old results aren't replaced, but returned.
TO ELABORATE:
int fact(int n)
{
int result;
if(n==1)
return 1;
result = fact(n-1) * n;
return result;
}
Assume a call to fact(2)
:
int result;
if ( n == 1 ) // false, go to next statement
result = fact(1) * 2; // calls fact(1):
|
|fact(1)
| int result; //different variable
| if ( n == 1 ) // true
| return 1; // this will return 1, i.e. call to fact(1) is 1
result = 1 * 2; // because fact(1) = 1
return 2;
Hope it's clearer now.