0
0
CConceptBeginner · 3 min read

What is argc and argv in C: Explanation and Example

argc and argv are parameters of the main function in C that allow a program to receive input from the command line. argc counts how many arguments are passed, and argv is an array of strings holding each argument.
⚙️

How It Works

Imagine you are giving instructions to a friend by writing a list of words on a piece of paper. In C, argc tells the program how many words (arguments) you wrote, and argv holds each word separately so the program can read them one by one.

When you run a C program from the command line, you can add extra information after the program name. This extra information is passed to the program as arguments. The first argument (argv[0]) is always the program's name, and the rest are the inputs you provide. argc counts all these arguments including the program name.

💻

Example

This example shows how to print all command-line arguments passed to a C program.

c
#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;
}
Output
Number of arguments: 3 Argument 0: ./program Argument 1: hello Argument 2: world
🎯

When to Use

You use argc and argv when you want your program to accept input from the user at the time it starts. This is useful for tools that need options or file names without asking inside the program.

For example, a program that copies files might take the source and destination file names as command-line arguments. Another example is a calculator program that takes numbers and operations as arguments to perform calculations immediately.

Key Points

  • argc counts all arguments including the program name.
  • argv is an array of strings holding each argument.
  • argv[0] is always the program's name or path.
  • Arguments are passed as strings; you may need to convert them to numbers if needed.
  • Using argc and argv helps make flexible command-line programs.

Key Takeaways

argc tells how many command-line arguments are passed to the program.
argv holds the actual arguments as strings in an array.
The first argument argv[0] is the program's name.
Use argc and argv to make programs accept input when they start.
Arguments are strings and may need conversion for other data types.