Command Line Argument


A command line argument is considered as an argument that is passed to the program when the program is invoked. Command line argument is used in C programming language when we have to control the program from outside. The command line argument is passed to the main () function of the program. The following is the syntax of using the command line argument:

SYNTAX:

int main ( int argc, char *argv [])

In the above syntax argc is used to count the arguments on command line and argv [] is a pointer which is used to hold all the pointers of character type that point to the arguments passed to program.


Example for command line argument:

Consider the following example for command line argument:

CODE:

#include <stdio. h>

#include <conio. h>

int main ( int argc, char *argv [] )

{

  int x;

  if ( argc > = 2 )

   {

    printf (“Number of arguments\n”);

    for (x = 1; x < argc; x++)

    {

     printf (“%s\t”, argv [x]);

    }

   }

   else

   {

     printf (“List of arguments is empty\n”);

   }

 getch ();

 return 0;

}

It should be noted here that argv [0] is used to hold the name of the program and argv [1] is used to point to the first command line argument, in this way argv [n] points to the last argument. If we do not provide an argument then “argc” will be one.