Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are recursive main() calls not allowed in C++? [duplicate]

Tags:

c++

main

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?

like image 872
gablin Avatar asked Mar 16 '11 14:03

gablin


People also ask

Can main () be called recursively in C?

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.

Can you recursively call Main () from main ()?

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.

What happens when the recursion calling is applied on two functions?

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.

Can a recursive method call itself more than once?

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.


1 Answers

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.

like image 82
user662630 Avatar answered Sep 17 '22 13:09

user662630