C Command Line Arguments

C makes it possible to pass values from the command line at execution time in your program. In this chapter, you will learn about the use of command-line argument in C.

The main() function is the most significant function of C and C++ languages. This main() is typically defined having a return type of integer and having no parameters; something like this:

Example:
int main()
{

    /* body of the main() function */
}

C provides programmers to put command-line arguments within the program, which will allow users to add values at the very start of program execution.

What are Command line arguments?

Command line arguments are the arguments specified after the program name in the operating system's command line, and these arguments values are passed to your program at the time of execution from your operating system. For using this concept in your program, you have to understand the complete declaration of how the main function works with this command-line argument to fetch values that earlier took no arguments with it (main() without any argument).

So you can program the main() is such a way that it can essentially accept two arguments where the first argument denotes the number of command line arguments whereas the second argument denotes the full list of every command line arguments. This is how you can code your command line argument within the parenthesis of main():

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

In the above statement, the command line arguments have been handled via main() function, and you have set the arguments where

  • argc (ARGument Count) denotes the number of arguments to be passed and
  • argv [ ] (ARGument Vector) denotes to a pointer array that is pointing to every argument that has been passed to your program.

You must make sure that in your command line argument, argv[0] stores the name of your program, similarly argv[1] gets the pointer to the 1st command line argument that has been supplied by the user, and *argv[n] denotes the last argument of the list.

Program for Command Line Argument

Example:
#include <stdio.h> 

int main( int argc, char *argv [] )
{
    printf(" \n Name of my Program %s \t", argv[0]);

    if( argc == 2 )
    {
        printf("\n Value given by user is: %s \t", argv[1]);
    }
    else if( argc > 2 )
    {
        printf("\n Many values given by users.\n");
    }
    else
    {
        printf(" \n Single value expected.\n");
    }
}
Output:


Scroll Back to Top