The main function

The main function is the starting point for running a program. The statements within the main function are executed sequentially. There maybe calls to other functions. A program usually stops running at the end of the main function, although it can stop at other points in the program.

Syntax

By default, the main has the storage class extern and a return type of integer or 'int'. It can also be declared to return void.

In C++ it is now ill-formed to declare main to return void. The practice is so common, though, that VisualAge C++ only gives a warning. Even in C it is not good practice to return void.

The optional parameters that main will accept, are used for programs that execute on the command line and receive initial arguments. If arguments are to be accepted from the command line, the valid parameters include the following:

argc contains the number of arguments entered at the command line. It has type int.
argv contains the actual arguments entered at the command line. It is an array of pointers to char array objects.
envp is an optional environmental pointer. It is an array of pointers to char objects that are the environment variables available to the program.

For example, the following 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 the program from a command line with the following:

backward string1 string2

will yield the output:

string2 string1