Chapter 13. Taking Command Line Arguments

13.1. How does C handle command line arguments?

A program starts by the operating system calling a programs main() function. Every one of your programs so far have defined main() as a function taking no arguments but this is not always the case. main() is the only function in C that can be defined in multiple ways. It can take no arguments, two arguments or three arguments. The two and three argument forms allow it to receive arguments from the shell. The three argument form is not particularly useful and is never necessary, we'll cover it briefly at the end of this chapter.

The two argument form takes an int and an array of strings. When defining main() you can give these arguments any name but it is convention to call them argc and argv[]. The first argument holds a count of how many elements there are in the array of strings passed as the second argument. The array is always null terminated so argv[argc] == NULL.

Here's a short program demonstrating the use of

Example 13-1. list_args.c

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

  for(i = 0; i < argc; i++)
    printf("argv[%d] == %s\n", i, argv[i]);

  return 0;
to be passed to main() via two arguments: an int and a *char[] (an array of strings). The int is usually called argc which is short for "argument count", as the name suggests, it stores the number of arguments passed to main(). The second argument, usually called argv is an array of strings.