Possible Duplicates:
restrictions on the main() function
Is it legal to recurse into main() in C++?
I read in C++ Primer that main
is not allowed to be called recursively, and in some related questions here on SO it is indeed confirmed that it is illegal.
But why is it illegal? As long as you avoid a stack overflow, what's the problem with calling main
within itself?
In 'C', the "main" function is called by the operating system when the user runs the program and it is treated the same way as every function, it has a return type. Although you can call the main() function within itself and it is called recursion.
Yes, we can call the main() within the main() function. The process of calling a function by the function itself is known as Recursion. Well,you can call a main() within the main() function ,but you should have a condition that does not call the main() function to terminate the program.
The two functions are called in an indeterminate order, and once both have been called their return values are added together and returned. The left function could be called first, or the right one first, you don't know. That may seem problematic, but it's not, because the order they're called doesn't matter.
A recursive implementation may have more than one base case, or more than one recursive step. For example, the Fibonacci function has two base cases, n=0 and n=1.
Well, the standard states:
3.6.1.3 "The function main shall not be used within a program."
5.2.2.9 "Recursive calls are permitted, except to the function named main"
I guess it is beause main() is a special function used as the entry point to the program. I'd say keep it special, don't take it down the level of a normal function, because it is not.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With