What are Command-Line Arguments?

Command-line arguments are simple parameters that are given on the system's command line, and the values of these arguments are passed on to your program during program execution. When a program starts execution without user interaction, command-line arguments are used to pass values or files to it.


What are Command-Line Arguments in C?

  • When the main function of a program contains arguments, then these arguments are known as Command Line Arguments.
  • The main function can be created with two methods: first with no parameters (void) and second with two parameters. The parameters are argc and argv, where argc is an integer and the argv is a list of command line arguments.
  • argc denotes the number of arguments given, while argv[] is a pointer array pointing to each parameter passed to the program. If no argument is given, the value of argc will be 1.
  • The value of argc should be non-negative.

                        * Main function without arguments:

                                    int main()

                        * Main function with arguments:

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



Properties of Command Line Arguments in C

  • Command line arguments in C are passed to the main function as argc and argv.
  • Command line arguments are used to control the program from the outside.
  • argv[argc] is a Null pointer.
  • The name of the program is stored in argv[0], the first command-line parameter in argv[1], and the last argument in argv[n].
  • Command-line arguments are useful when you want to control your program from outside rather than hard coding the values inside the code.
  • To allow the usage of standard input and output so that we can utilize the shell to chain commands.
  • To override defaults and have more direct control over the application. This is helpful in testing since it allows test scripts to run the application.

 

Advantages of Command-Line Arguments in C

  • A command-line argument allows us to provide an unlimited number of arguments.
  • The data is passed as strings as arguments, so we can easily convert it to numeric or other formats.
  • It is useful for configuration information while launching our application.