It is usually expressed as
int main( int argc, char* argv[] )
where the postscript 'c' means 'count' and 'v' means 'variable-length'.
When you execute a program from the command-line, you type its name followed by zero or more argument strings. For example:
(Windows)
dir /b *.txt
(Unix)
ls -CF foo.txt
In both of these examples, the program is executed with two arguments --which are themselves character strings:
'dir' has arguments "/b" and "*.txt"
'ls' has arguments "-CF" and "foo.txt"
The trick is that the actual number of arguments the user will type is unknown. So the
main() function in a C or C++ program simply gives you an array of char* and the number of elements in that array. (It also treats the program name as the first argument.)
To play with it, compile and play with the following program:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
|
#include <iomanip>
#include <iostream>
using namespace std;
int main( int argc, char* argv[] )
{
cout << "Program \"" << argv[ 0 ] << "\" was run with " << (argc -1) << " arguments:\n";
for (int n = 1; n < argc; n++)
{
cout << setw( 2 ) << n << " \"" << argv[ n ] << "\"\n";
}
return 0;
}
|
If I were to compile it to
a.exe, I could try:
a.exe
a.exe hello world
a.exe x - y + z
a.exe 42
a.exe "hello world"
|
Hope this helps.