C and C++ have a special argument list for main( ), which looks like this:
int main(int argc, char* argv[ ]) { // ...
The first argument is the number of elements in the array, which is the second argument. The second argument is always an array of char*, because the arguments are passed from the command line as character arrays (and remember, an array can be passed only as a pointer). Each whitespace-delimited cluster of characters on the command line is turned into a separate array argument. The following program prints out all its command-line arguments by stepping through the array:
Example:
#include
int main(int argc, char* argv[ ]) {
cout << "argc = " << argc << endl;
for(int i = 0; i < argc; i++)
cout << "argv[" << i << "] = "
<< argv[i] << endl;
}
You’ll notice that argv[0] is the path and name of the program itself. This allows the program to discover information about itself. It also adds one more to the array of program arguments, so a common error when fetching command-line arguments is to grab argv[0] when you want argv[1].
You are not forced to use argc and argv as identifiers in main( ); those identifiers are only conventions (but it will confuse people if you don’t use them). Also, there is an alternate way to declare argv:
int main(int argc, char** argv) { // ...
Both forms are equivalent