Can we have two main()
functions in a C++ program?
No, you cannot have more than one main() function in C language. In standard C language, the main() function is a special function that is defined as the entry point of the program.
it's not possible in c to have more than 1 main-function. you could use preprocessor directives like "#ifdef" to compile just one main-function at the time.
The main function serves as the starting point for program execution. It usually controls program execution by directing the calls to other functions in the program.
The standard explicitly says in 3.6.1:
A program shall contain a global function called main, which is the designated start of the program. [...] This function shall not be overloaded.
So there can one only be one one main
function in the global scope in a program. Functions in other scopes that are also called main
are not affected by this, there can be any number of them.
Only one function can be named main
outside of any namespace, just as for any other name. If you have namespaces foo
and bar
(etc) you can perfectly well have functions named foo::main
, bar::main
, and so on, but they won't be treated as anything special from the system's point of view (only the function named main
outside of any namespace is treated specially, as the program's entry point). Of course, from your main
you could perfectly well call the various foo::main
, bar::main
, and so on.
Yes! Why not?
Consider the following code:
namespace ps
{
int main(){return 0;}
}
int main()
{
ps::main();
}
Its ::main()
that will be called during execution.
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