In the latter case the compiler might be able to optimize out things that it can evaluate already during compilation. That should be easy to test. Test with:
1 2 3 4 5 6 7 8
|
int main()
{
int value=1;
cin >> value;
cout << factorial( value );
system("pause");
return 0;
}
|
The first version has a
recursive function. Use that as keyword in searches.
The main() calls factorial(5), so within the function call the a==5 and the condition is false, so the effective content is:
return 5 * factorial(4);
Again, when the a==4, we get a similar result:
return 4 * factorial(3);
Lets inject/replace that into the first function calls statement:
return 5 * (4 * factorial(3));
Lets continue couple more times, until we reach:
return 5 * (4 * (3 * (2 * factorial(1))));
Now we are "deep enough" to call the recursive function with a value that triggers "end condition" that stops the recursion from going any deeper/further. A proper end condition is very important.
The if-clause will be true, and therefore the factorial(1) will return 1. We will put that in the expression too. The
cout << factorial(5);
is thus essentially same as:
cout << (5*4*3*2*1);