Go to the first, previous, next, last section, table of contents.


Program Arguments

The system starts a C program by calling the function main. It is up to you to write a function named main---otherwise, you won't even be able to link your program without errors.

In ISO C you can define main either to take no arguments, or to take two arguments that represent the command line arguments to the program, like this:

int main (int argc, char *argv[])

The command line arguments are the whitespace-separated tokens given in the shell command used to invoke the program; thus, in `cat foo bar', the arguments are `foo' and `bar'. The only way a program can look at its command line arguments is via the arguments of main. If main doesn't take arguments, then you cannot get at the command line.

The value of the argc argument is the number of command line arguments. The argv argument is a vector of C strings; its elements are the individual command line argument strings. The file name of the program being run is also included in the vector as the first element; the value of argc counts this element. A null pointer always follows the last element: argv[argc] is this null pointer.

For the command `cat foo bar', argc is 3 and argv has three elements, "cat", "foo" and "bar".

If the syntax for the command line arguments to your program is simple enough, you can simply pick the arguments off from argv by hand. But unless your program takes a fixed number of arguments, or all of the arguments are interpreted in the same way (as file names, for example), you are usually better off using getopt to do the parsing.

In Unix systems you can define main a third way, using three arguments:

int main (int argc, char *argv[], char *envp)

The first two arguments are just the same. The third argument envp gives the process's environment; it is the same as the value of environ. See section Environment Variables. POSIX.1 does not allow this three-argument form, so to be portable it is best to write main to take two arguments, and use the value of environ.


Go to the first, previous, next, last section, table of contents.