What is command line argument?

The argument passed to the main() function while executing the program is known as command line argument.

In C programming, command line arguments are parameters passed to a program when it is executed from the command line or terminal. These arguments allow users to customize the behavior of the program without modifying its source code.

In the main() function declaration in C, you’ll typically see argc and argv parameters. Here’s a breakdown:

  • argc (argument count): This variable holds the number of arguments passed to the program, including the name of the program itself.
  • argv (argument vector): This is an array of strings (char* argv[]), where each element is a pointer to a string that represents one of the command line arguments. argv[0] holds the name of the program, while argv[1], argv[2], and so on hold the actual command line arguments passed.

For example, if you run a C program named myprogram from the command line as follows:

bash
./myprogram arg1 arg2

Then, argc will be 3 (including the program name) and argv will be an array containing:

  • argv[0] = “./myprogram”
  • argv[1] = “arg1”
  • argv[2] = “arg2”

Programmers can use these command line arguments to make their programs more flexible and configurable based on user input.