A beginner problem

Hello, i am very beginner of c++. While i learnig it, i have seen a code that shows factorial of a number. I did not understand the code when i looked first. Then typed it to visual basic and watched it over step by step in debugger. And i still dont understand and get confused.

Main Code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>
using namespace std;
int factorial(int a)
{
	if (a == 1)
	return 1;
	return a*factorial(a - 1);
}
int main()
{
	cout << factorial(5);
	system("pause");
	return 0;
}


then i changed it to make it easy to understand as:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>
using namespace std;
int factorial(int a)
{
	if (a == 1)
	return 1;
	return 10;
}
int main()
{
	cout << factorial(5);
	system("pause");
	return 0;
}


When i changed it i was shocked. Because in debugger, processor shows the value of factorial function without not going to check If function. And number 10 is being printed. Can you help me about understanding this?
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);
Thanks for your answer. Now i can see how it works.
Topic archived. No new replies allowed.