C++ - Calling a function inside the same function's definition
c++, function, recursion
Solution
A function calling itself is known as a recursive function. This works because the compiler only needs the declaration of a function, not its definition, for you to be able to call it. The first line of the definition also serves as a declaration. (For details, see § 8.4.1.2 of the C++11 standard.)
Recursion is well-suited to solve many problems. The typical example of a recursive function is the `factorial` function. It is defined as `factorial(n) = n * factorial(n-1)`.
You can try running this piece of code to get a bit more understanding of what happens when a function calls itself:
#include <iostream>
int factorial(unsigned int n)
{
std::cout << "Computing factorial of " << n << "\n";
int result;
if (n == 0) {
result = 1;
} else {
result = n * factorial(n-1);
}
std::cout << "factorial(" << n << ") = " << result << "\n";
return result;
}
int main()
{
factorial(5);
}
For more information about declaration vs. definition, see this answer. The Wikipedia page about the One Definition Rule might also be helpful.
Problem
I was writing something similar to the code below and I accidentally called the same function inside the body of the function definition. ``` double function(double &value) { //do something with a here if(some condition) { function(a); } return a; } ``` Consider something of the form: ``` int function(int &m) { m = 2*m; if(m < 20) { function(m); } return m; }; int main() { int a = 2; std::cout <<"Now a = "<<function(a); return 1; } ``` According to me this should not run let alone compile. But it does run and gives out the correct result Now a = 32 I have called the function before I even 'finished' defining it. Yet, it works. Why?