Command-line argumentssuggest change
- int main(int argc, char *argv)
Parameter | Details |
—— | —— |
argc | argument count - initialized to the number of space-separated arguments given to the program from the command-line as well as the program name itself. |
argv | argument vector - initialized to an array of
char-pointers (strings) containing the arguments (and the program name) that was given on the command-line. |
A C program running in a ‘hosted environment’ (the normal type — as opposed to a ‘freestanding environment’) must have a
main function. It is traditionally defined as:
int main(int argc, char *argv)
argv can also be, and very often is, defined as
char **argv; the behavior is the same. Also, the parameter names can be changed because they’re just local variables within the function, but
argv are conventional and you should use those names.
main functions where the code does not use any arguments, use
Both parameters are initialized when the program starts:
argcis initialized to the number of space-separated arguments given to the program from the command-line as well as the program name itself.
argvis an array of
char-pointers (strings) containing the arguments (and the program name) that was given on the command-line.
- some systems expand command-line arguments “in the shell”, others do not. On Unix if the user types
myprogram *.txtthe program will receive a list of text files; on Windows it will receive the string “
Note: Before using
argv, you might need to check the value of
argc. In theory,
argc could be
0, and if
argc is zero, then there are no arguments and
argv (equivalent to
argv[argc]) is a null pointer. It would be an unusual system with a hosted environment if you ran into this problem. Similarly, it is possible, though very unusual, for there to be no information about the program name. In that case,
argv == '\0' — the program name may be empty.
Suppose we start the program like this:
./some_program abba banana mamajam
argc is equal to
4, and the command-line arguments:
"./some_program"(the program name) if the program name is available from the host environment. Otherwise an empty string
argvcontains the value
See also What should
main() return in C and C++ for complete quotes from the standard.