by Dinesh Thakur Category: Functions

Like C, C++ enables to pass arguments to the main () function also. These arguments are passed by typing them after the program name on the command line. Hence, these arguments are known as command line arguments. Command line arguments help in providing data to the program.


The syntax of passing command line arguments is

program_name <arg1> <arg2>…………. <argN>


program_name = name of the program run from command line

<arg1> <argN> = name of argument passed to the program separated by a space

In C++, three arguments are passed to main () : argc, argv and envp


• The first argument argc of type int is the Argument Count, which counts the number of command line arguments passed to the program, including the program name.

• The second argument argv of the type array of char* is the Argument Vector, which holds the command line arguments. The first character array is argv [0] that stores the program name and the remaining elements represent the arguments supplied to the program.

• The third argument envp of the type array of char* is an optional argument that holds the current settings for any environment block variables.

The function header of main ()with arguments is written as

int main{int argc, char* argv[], char* envp[])


It can also be written as

int main{int argc, char *argv[], char *envp[])


To understand the concept of arguments to main(),consider this example.


Example : A program to demonstrate the concept of command line arguments



using namespace std;

int main{int argc, char *argv[], char *envp[])


Cout<<”Number of arguments (argc) is “<<argc<<endl;

Cout<<”Program name is "<<argv[0];

Cout<<”\nOther arguments are "<<endl;

for (int i = 1; i < argc; i++)

cout <<”argv["<<i<<”] = "<<argv[i] <<endl;

cout<<”\nEnvironmental Settings are "<<endl;

for (int i = 0; i < argc; i++)

cout <<”envp["<<i<<"]="<<envp[i] <<endl;

return 0i


Save the file as args.cpp and then run the program from command line using this statement.

args hello world


The output of the program is

Number of arguments (argc) is 3

Program name is C:\args.exe

Other arguments are



Environmental Settings are

envp [0]== ::= ::\

envp [1]==c: =c: \

envp [2]=ALLUSERSPROFILE=C: \Documents and Settings\All Users

In this example, two strings hello and world are passed as command-line arguments with the name of the program args. The contents of argc and argv are shown in Figure.

                        Contents of argc and argv

About Dinesh Thakur

Dinesh ThakurDinesh Thakur holds an B.SC (Computer Science), MCSE, MCDBA, CCNA, CCNP, A+, SCJP certifications. Dinesh authors the hugely popular blog. Where he writes how-to guides around Computer fundamental , computer software, Computer programming, and web apps. For any type of query or something that you think is missing, please feel free to Contact us.

Related Articles