main function

Hi,
I have seen the main function declared as follows:
1
2
3
4
int main(int argc, char **argv)
{
  ...
}

What actually are argc and argv, I mean what do they stand for, and what is this kind of main function used for?...its kinda of strange to me.

cheers.
Last edited on
argc - refer to the number of command line arguments
char **argv - refer to the actual "value" of those individual command line arguments
More specifically, argv is an array of char*'s. Which means that when your program is called Bob.exe, and it's located in the C:/ directory and you call it with 2 arguments respectively called Lolol and Foo:
C:/Bob.exe Lolol Foo
argc equals 3
argv[0] equals "C:/Bob.exe"
argv[1] equals "Lolol"
argv[2] equals "Foo"
Note how argv[0] always equals the full directory and executable name of the program being executed.
Note how argv[0] equals the command by which the program was called.

RE-EDIT:
Forgot the main part of the question (What do they stand for):
I believe they are shorter ways to write:
argument count
argument values argument vector
Although I'm not sure about the latter.

Changed some of my mistake's based on m4ster r0shi's advice.
Last edited on
I almost agree with Kyon.

-> argv[0] is the command by which the program was called
-> 'argv' stands for 'argument vector'
Sohguanh is right & so is Kyon except for the fact that argv[0] has the full directory & executable name of the program being executed which is in-correct. argv[0] only has the program name and does not include the complete path for the program. You may run the following program in *NIX or Windows to verify the same. This program prints the individual command line arguments on a separate line. If you name the program as "command" and pass "1", "2" and "3" as arguments, you will get the following output:

command
1
2
3


1
2
3
4
5
6
7
8
9
10
#include <vector>
#include <iostream>
#include <algorithm>
#include <iterator>
using namespace std;
int main(int argc, char* argv[])
{
	vector<string> v(argv, argv + argc);
	copy(v.begin(), v.end(), ostream_iterator<string>(cout, "\n"));	
}
Last edited on
A more sophisticated way of doing that is this:
1
2
3
4
5
6
#include <iostream>

int main(int argc, char** argv)
{
   for(int i = 0; i < argc; i++ ) std::cout << argv[i];
}
Last edited on
And to complete the number of different ways to print out the arguments, there's always boost.lambda:

 
std::for_each( argv, argv + argc, std::cout << boost::lambda::_1 << '\n' );
Topic archived. No new replies allowed.