Chapter 33 of 37

Command-Line Arguments

Normally, we provide input to a C program while the program is running using functions like scanf().

But C also allows us to provide input when starting the program.

These inputs are called command-line arguments.

What are Command-Line Arguments?

Command-line arguments are values passed to a program when it is executed from the command line.

For example:

program John 20

Here, John and 20 are command-line arguments.


argc and argv

To access command-line arguments, we use two parameters in the main() function:

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

argc

argc stands for argument count.

It tells us how many command-line arguments were provided, including the program name itself.

argv

argv stands for argument vector.

It is an array of strings containing the arguments.

For example, if we run:

program John 20

then conceptually:

argv[0] → program
argv[1] → John
argv[2] → 20

So argc would be 3.


Simple Example

#include <stdio.h>

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

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

    return 0;
}

If we run:

program Hello World

the output will be similar to:

Argument count: 3
program
Hello
World

The exact value of argv[0] depends on how the program was invoked.


Important Point

Command-line arguments are received as strings.

So if we pass:

program 25

the 25 in argv[1] is text, not an int.

If we need to use it as a number, we need to convert it.

For example, atoi() from <stdlib.h> can convert a simple numeric string:

int age = atoi(argv[1]);

For more robust input handling, functions such as strtol() are generally preferred because they provide better error checking.

In Simple Words

Command-line arguments allow us to pass input to a C program when starting it from the command line.

Remember:

argc → Number of arguments
argv → Array containing the arguments

And the basic main() structure is:

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

Command-line arguments are especially useful for command-line tools, scripts, configuration options, and programs that need input before execution begins.