Is it possible to integrate the concepts of inline functions and recursion in c++(i.e. creating an inline recursive function)? if yes, write a program to support your answer. if not, why?
Answers
Answered by
2
There's ultimately no reason why you can't create a function which is both inline and recursive.
A recursive function is one which calls itself and hence pushes its new instances as and when called in the stack.
An inline function is one which in order to reduce the number of stack calls and return times replaces the statement which called it with the definition of the function along with the arguments (if any) with the originally passed ones.
Now if you merge the two concepts, you'll realize that an inline recursive function will simply replace the statement with the function definition, and when the recursive function will call itself again, the function being inline again will replace that very statement with the definition. This cycle will continue until it reaches the base case and terminates.
Here's a program to demonstrate the same:
inline int fact(int n)
{
return n != 0 ? n * fact(n-1) : 1;
}
int main()
{
std :: cout << fact(3);
}
Now, fact(3) will be replaced with
3 * fact(2) in main(). Now, fact(2) will be replaced with 2 * fact(1) in the main. This will continue till fact(0) is being called, when the statement in main will look like:
cout << 3 * 2 * 1 * 1;
So, that's it.
A recursive function is one which calls itself and hence pushes its new instances as and when called in the stack.
An inline function is one which in order to reduce the number of stack calls and return times replaces the statement which called it with the definition of the function along with the arguments (if any) with the originally passed ones.
Now if you merge the two concepts, you'll realize that an inline recursive function will simply replace the statement with the function definition, and when the recursive function will call itself again, the function being inline again will replace that very statement with the definition. This cycle will continue until it reaches the base case and terminates.
Here's a program to demonstrate the same:
inline int fact(int n)
{
return n != 0 ? n * fact(n-1) : 1;
}
int main()
{
std :: cout << fact(3);
}
Now, fact(3) will be replaced with
3 * fact(2) in main(). Now, fact(2) will be replaced with 2 * fact(1) in the main. This will continue till fact(0) is being called, when the statement in main will look like:
cout << 3 * 2 * 1 * 1;
So, that's it.
Similar questions