Home » Tutorials » C++ Programming » 1.1. Getting started with C++ » 1.1.1. Basic program structure » 1.1.1.1. main() with command line arguments

There is an alternative for the main() function which allows command-line options to be sent to the program:

 

int main(int argc, char* argv[])
{
for(int i=0; i<argc; ++i)
{
std::cout << i << " : " << argv[i] << std::endl;
}
}

 

In this short sample, argv is an array of values, and argc is a count of the elements in the argv array. The code inside the main() function will be discussed in more detail in another section, but what's important to note here is that argv[0] is the name of the program being run, and argv[argc-1] is the last command-line option provided by the user. The -1 is necessary because arrays start at zero.