Command-line arguments are inputs passed to a program when it is invoked from the command line interface of an operating system. They provide a simple way to customize the behavior of a program without having to change the program’s source code. In C programming, command-line arguments are typically handled within the main() function, which is the entry point of the program.

The signature of the main() function, when command-line arguments are to be used, is as follows:

int main(int argc, char *argv[]) {
    // ...
}

Here’s the breakdown of the parameters:

  1. argc (Argument Count):
  • This parameter represents the count of arguments passed to the program, including the program name itself. So, if no arguments are passed, argc will be 1.
  1. argv (Argument Vector):
  • This is an array of character pointers (strings) where each pointer points to a null-terminated string that represents each argument passed to the program. The first string (argv[0]) is the name of the program itself, argv[1] is the first argument, argv[2] is the second argument, and so on.

Here is an example C program that demonstrates the usage of command-line arguments:

#include <stdio.h>

int main(int argc, char *argv[]) {
    for (int i = 0; i < argc; i++) {
        printf("Argument %d: %s\n", i, argv[i]);
    }
    return 0;
}

When compiled and run from the command line, this program will print each argument on a new line. For example, running the program with the command ./program arg1 arg2 would produce the following output:

Argument 0: ./program
Argument 1: arg1
Argument 2: arg2

This example demonstrates how command-line arguments can be accessed and used within a C program to influence its behavior based on user input.