There is a main that is like this.
int main(int argc, char *argv[]){
}
And another one that is just like this:
int main(){
}
So far I have used both and both have worked for me, so I have not identified what the difference is between using one or the other, or if they have different purposes.
In the first
main
argc: stores the amount (number) of parameters, including the name of the executable.
*argv[]: An array containing all received parameters 1 including the name of the executable.
if you use terminal many times you do things like this:
that's when through the first
main
but NOT the second, you can get those parameters and use them within your program to generate one behavior or another, check what parameter was passed, or the number of parameters that have been passed when executing your program etc.you can compile this example:
and run it like this for example:
Shell:
(if your program is called a.out)
the following code uses this syntax
char **argv
instead ofchar *argv[]
but is "basically" the same. One is more than c and the other is c++, some call it a two-dimensional array of characters and others an array of pointers to characters .1 *argv[]: array of pointers to characters.
The question itself has the answer: The arguments. Both versions will be considered the entry point of the program.
According to the C++ standard (my translation):
Thus, both signatures are correct and valid for
main
and the standard does not indicate that either version ofmain
should act differently.Both forms are valid and are the entry point for your application.
The first form
int main(int argc, char** argv)
receives the command line arguments (when the application is launched), in the form of: array of null-terminated strings (argv) and the number of strings in that array (argc).The second way
int main()
is simpler, preferred when the application doesn't need to read the command line arguments (ie, doesn't use them).Although you haven't mentioned it, it
main
should return 0 if execution was successful and non-0 if there was a failure. If you omit thereturn
, c++ assumes that you returned 0 (or success).