Command-Line Arguments
Every C program can receive input directly from the command line when it is launched. This is one of the oldest and most fundamental ways a program communicates with the outside world, and it is how nearly every command-line tool you have ever used (compilers, git, ls, grep) accepts options and filenames. C exposes this through two extra parameters to the main function.
The Two-Parameter main()
Instead of writing a plain int main(void), you can declare main with two parameters that the operating system fills in for you before your program starts running:
int main(int argc, char *argv[]) {
// argc: argument count
// argv: argument vector (array of C-strings)
return 0;
}argc (argument count) — an integer giving the number of command-line arguments.
argv (argument vector) — an array of C-strings (char*), one per argument.
argv[0] Is the Program Name
A very common beginner mistake is forgetting that argc includes the program's own name as the first entry. If you run a program like this:
./greet hello world
then inside main you will see:
Expression | Value |
|---|---|
argc | 3 |
argv[0] | "./greet" (the program name/path) |
argv[1] | "hello" |
argv[2] | "world" |
Worked Example: Echoing Arguments
Here is a complete program that prints every argument it receives, one per line, along with its index:
#include <stdio.h>
int main(int argc, char *argv[]) {
printf("Program name: %s\n", argv[0]);
printf("Number of user arguments: %d\n", argc - 1);
for (int i = 1; i < argc; i++) {
printf("argv[%d] = %s\n", i, argv[i]);
}
return 0;
}$ ./echo_args apple banana 42
Program name: ./echo_args Number of user arguments: 3 argv[1] = apple argv[2] = banana argv[3] = 42
Converting Arguments to Numbers
Command-line arguments always arrive as strings, even when they look like numbers. To use one as a number, you must convert it explicitly. The two most common tools for this are atoi and strtol, both declared in stdlib.h.
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[]) {
if (argc < 2) {
fprintf(stderr, "Usage: %s <number>\n", argv[0]);
return EXIT_FAILURE;
}
/* atoi: simple, but silently returns 0 for invalid input */
int a = atoi(argv[1]);
printf("atoi result: %d\n", a);
/* strtol: reports errors via errno and endptr */
char *endptr;
long b = strtol(argv[1], &endptr, 10);
if (endptr == argv[1]) {
fprintf(stderr, "Error: '%s' is not a valid number\n", argv[1]);
return EXIT_FAILURE;
}
printf("strtol result: %ld\n", b);
return EXIT_SUCCESS;
}Summary
int main(int argc, char *argv[]) receives command-line input from the OS.
argc counts all arguments including the program name; argv[0] is that name.
Real user arguments run from argv[1] through argv[argc - 1].
argv[argc] is guaranteed to be NULL.
Convert numeric arguments with strtol rather than atoi for real error checking.