C - Command-Line Arguments in C (argc and argv)

In C programming, command-line arguments allow users to pass input values to a program when it is executed from the command prompt or terminal. Instead of taking input during runtime using scanf(), the values are provided directly when running the program.

To use command-line arguments, the main() function must be written in this format:

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

Here:

  • argc stands for argument count. It stores the total number of arguments passed to the program.

  • argv stands for argument vector. It is an array of character pointers (strings) that stores each argument.

Important points:

  1. argc always has at least one value because the program name itself is counted as the first argument.

  2. argv[0] contains the program name.

  3. argv[1], argv[2], and so on contain the additional arguments passed by the user.

  4. All command-line arguments are stored as strings, even if they represent numbers. If you need to perform calculations, you must convert them using functions like atoi() or strtol().

Example Program:

#include <stdio.h>

int main(int argc, char *argv[])
{
    printf("Number of arguments: %d\n", argc);

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

    return 0;
}

How to run the program:

If the compiled program name is sample, you can run it like this:

Windows:

sample hello 25 world

Linux:

./sample hello 25 world

Output:

Number of arguments: 4
Argument 0: sample
Argument 1: hello
Argument 2: 25
Argument 3: world

Explanation of the output:

  • There are 4 arguments including the program name.

  • The values entered after the program name are stored in the argv array.

  • Even the number 25 is stored as a string.

Converting String Arguments to Integers:

If you want to add two numbers passed through the command line:

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char *argv[])
{
    if(argc != 3)
    {
        printf("Please provide two numbers.\n");
        return 1;
    }

    int num1 = atoi(argv[1]);
    int num2 = atoi(argv[2]);

    printf("Sum = %d\n", num1 + num2);

    return 0;
}

This program converts string inputs into integers and performs addition.

Why Command-Line Arguments Are Important:

  1. They allow automation of programs.

  2. They are useful in system-level and utility programs.

  3. They make programs flexible and reusable.

  4. They are commonly used in real-world applications like compilers, file processors, and system tools.

Command-line arguments are especially useful when writing professional-level C programs where user input must be given quickly and efficiently at execution time.