I am calling the factorial function defined in the following manner by reference.
int factorial(int &n) {
n--;
if (n>0) return factorial(n)*(n+1);
else return 1;
}
when I pass the value 5 it returns the value 1 as I'd expected. But when I define the factorial function in the following way it returns the factorial of 5 that is 120.
int factorial(int &n) {
n--;
if (n>0) return (n+1)*factorial(n);
else return 1;
}
I conjectured that the expression is evaluated in linear order and when a function is invoked in the expression all the values of local variables and the component expressions that have been evaluated so far in the original expression are stored and when the function returns control back to the caller these values that are retained are used in computation of the expression and not their modified values.
Is my hypothesis correct? Kindly enlighten me.