Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is main() overloaded in C++?

2 valid versions of main() exist in C++:

int main()  // version 1 int main(int argc, char **argv)  // version 2 

But both overloads cannot coexist at the same time. Why not? (Potential use case: while running the program from the terminal, if no arguments are passed the first version is called, otherwise the second version is.)

Does the compiler perform a special check to allow just one version per binary?

like image 259
iammilind Avatar asked Jun 20 '11 07:06

iammilind


People also ask

Can main () be overloaded?

Yes, we can overload the main method in Java, but When we execute the class JVM starts execution with public static void main(String[] args) method.

Can main function be overloaded in C?

Can main() be overloaded in C++? In C++, we can use the function overloading.

How main method is overloaded?

How to overload main method in java? Method Overloading can be defined as a feature in which a class can have more than one method having the same name if and only if they differ by number of parameters or the type of parameters or both, then they may or may not have same return type.

Why C has no function overloading?

This feature is present in most of the Object Oriented Languages such as C++ and Java. But C doesn't support this feature not because of OOP, but rather because the compiler doesn't support it (except you can use _Generic).


1 Answers

§3.6.1/2 (C++03) says

An implementation shall not predefine the main function. This function shall not be overloaded. It shall have a return type of type int, but otherwise its type is implementation-defined. All implementations shall allow both of the following definitions of main:

   int main() { /* ... */ }    int main(int argc, char* argv[]) { /* ... */ } 

You can use either of them. Both are standard compliant.

Also, since char *argv[] is equivalent to char **argv, replacing char *argv[] with char **argv doesn't make any difference.


But both the versions cannot co-exist at the same time ! (use case can be like: while running the binary from command prompt, if you pass no argument then 1st version should be called else the 2nd version).

No. Both versions cannot co-exist at the same time. One program can have exactly one main function. Which one, depends on your choice. If you want to process command-line argument, then you've to choose the second version, or else first version is enough. Also note that if you use second version, and don't pass any command line argument, then there is no harm in it. It will not cause any error. You just have to interpret argc and argv accordingly, and based on their value, you've to write the logic and the flow of your program.

like image 168
Nawaz Avatar answered Sep 28 '22 17:09

Nawaz