Command-line Arguments
suggest changeIn a hosted C implementation, main may be defined with two parameters:
int main(int argc, char *argv[])
char **argv is an equivalent parameter declaration. The names argc and argv are conventional but not required.
| Parameter | Meaning |
|---|---|
argc |
A nonnegative count of arguments. |
argv |
An array of pointers to strings supplied by the host environment. |
If argc is greater than zero, argv[0] points to a string representing the program name; that string may be empty when the name is unavailable. Elements argv[1] through argv[argc - 1] are the remaining arguments, and argv[argc] is a null pointer.
For example, a shell might start a program as follows:
./some_program abba banana mamajam
The program would commonly receive argc == 4, with the four corresponding strings in argv[0] through argv[3]. How command text is parsed, quoted, and expanded is determined by the host environment or command interpreter, not by C. Do not assume arguments are simply split at spaces.
Check argc before accessing an optional element:
#include <stdio.h>
int main(int argc, char *argv[])
{
if (argc < 2) {
fprintf(stderr, "usage: %s NAME\n",
argc > 0 ? argv[0] : "program");
return 2;
}
printf("Hello, %s!\n", argv[1]);
return 0;
}
Use int main(void) when the program does not need arguments. Freestanding implementations may define program startup differently.