What int argc and char *argv[] means in C or C++ programming language ?
![](/image/blogThumbl57HeFBmth.png)
When you run a program in command line interface, you can transmit data to that program through command line arguments before it runs.
In C or C++ programs these data will be given to the program through it's main function (the entry point of the program) arguments.
The main function looks like this :
int main(int argc, char* argv[]){
return 0;
}
What int argc and char *argv[] represent ?
char *argv[]
is the second argument of the main function, it's an array of strings. These strings are the names of the command line arguments passed to the program.
Example :
With this command :
./program hello from grenierdudev
the char *argv[] will contains :
argv[0] = is always the name of the executable, so it's ./program
argv[1] = is the name of the first argument, so it's hello
argv[2] = is the name of the second argument, so it's from
argv[3] = is the name of the third argument, so it's grenierdudev
int argc
is the of elements in the argv array. In the previous command line example argc is 4.
Example to illustrate
Create a C++ file and copy this code inside :
#include <iostream>
int main(int argc, char* argv[]){
std::cout << "argc = " << argc << std::endl;
for (int i = 0; i < argc; i++)
{
std::cout << "argv["<<i<<"] = "<< argv[i] << std::endl;
}
return 0;
}
To compile and run it :
// to compile
g++ program.cpp -o program
// to run
./program hello from grenierdudev
The result :