The main() function

When a program begins running, the system calls the function main, which marks the entry point of the program. By default, main has the storage class extern. Every program must have one function named main, and the following constraints apply:

The function main can be defined with or without parameters, using any of the following forms:

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

Although any name can be given to these parameters, they are usually referred to as argc and argv. The first parameter, argc (argument count) is an integer that indicates how many arguments were entered on the command line when the program was started. The second parameter, argv (argument vector), is an array of pointers to arrays of character objects. The array objects are null-terminated strings, representing the arguments that were entered on the command line when the program was started.

The first element of the array, argv[0], is a pointer to the character array that contains the program name or invocation name of the program that is being run from the command line. argv[1] indicates the first argument passed to the program, argv[2] the second argument, and so on.

The following example program backward prints the arguments entered on a command line such that the last argument is printed first:

#include <stdio.h>
int main(int argc, char *argv[])
{
  while (--argc > 0)
    printf("%s ", argv[argc]);
}

Invoking this program from a command line with the following:

   backward string1 string2

gives the following output:

   string2 string1

The arguments argc and argv would contain the following values:

Object Value
argc 3
argv[0] pointer to string "backward"
argv[1] pointer to string "string1"
argv[2] pointer to string "string2"
argv[3] NULL

Related information