int main(int argc, char** argv)
The argc
parameter is the number of command line options specified, including the executable name, when the executable was invoked. The individual command line options are found in the argv
array, which is NULL
terminated (the name and path used to invoke the executable is in argv[0]
).
The difference between the two versions is simply if you want to parse command line arguments or not - if you are not interested in them then you can ignore them using the second form.
Wikipedia offers a good explanation. The first parameter gives you the number of command line arguments, and the second gives you the actual arguments.
They represent the command line parameters.
argc is the number of command line parameters, including the name of the executable.
argv is an array of null-terminated strings, where argv[0]
is the command line parameter, and argv[i]
is the ith parameter after that, argv[argc-1]
being the last one and argv[argc]
is actually well defined and a NULL pointer.
Thus:
foo bar baz
on the command line will have argc
=3, argv[0]
="foo" argv[1]
="bar" argv[2]
="baz" argv[3]
= NULL
Note that there is no special attachment placed for "flag" arguments.
grep -i foo bar.cpp bar.h
would have 4 arguments (argc=5 including grep itself), -i being one of them and this would apply even if the next parameter was a "value" attached to the flag.
Note if you did a wildcard
grep -i foo *
in UNIX at least, the * would be expanded before the call into grep and thus each file that matched would be an argument.
Incidentally
char** argv
and char* argv[]
do the same thing.
Also while the standard says you must use one of these signatures (you shouldn't even add in any consts) there is no law you have to use those two variable names, but it is so conventional now that they are pretty much universal. (i.e. you could use argCount
and argValues
if you want).