C Command Line Arguments
C programs can receive input directly when they're launched, via command line arguments. These are captured through main()'s optional parameters: argc (argument count) and argv (argument values).
argv[0] is always the program's own name, and subsequent elements argv[1], argv[2], etc., are the arguments the user typed after the program name.
int main(int argc, char *argv[]) { ... }argc and argv
argc holds the total number of arguments (including the program name). argv is an array of C strings, one per argument, with argv[argc] guaranteed to be NULL.
Using arguments
Since argv elements are strings, numeric arguments must be converted using functions like atoi() or strtol() before being used in calculations.
#include <stdio.h>
int main(int argc, char *argv[]) {
printf("Program: %s\n", argv[0]);
printf("Arg count: %d\n", argc);
return 0;
}Program: ./myapp
Arg count: 1Run as `./myapp` with no extra arguments, argc is 1 and argv[0] is the program name.
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[]) {
if (argc > 1) {
int n = atoi(argv[1]);
printf("Doubled: %d\n", n * 2);
}
return 0;
}Doubled: 10Running `./myapp 5` converts argv[1] ("5") to an int with atoi, then doubles it.
Key points
- argc counts the arguments; argv holds them as an array of strings.
- argv[0] is always the program's own name.
- Use atoi()/strtol() to convert string arguments into numbers.
- argv[argc] is guaranteed to be a NULL pointer.
