5.5 The main Function

figs/acorn.gif

Every program must have a function in the global namespace called main, which is the main program. This function must return type int. The C++ environment calls main; your program must never call main. The main function cannot be declared inline or static. It can be called with no arguments or with two arguments:

int main(  )

or:

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

The argc parameter is the number of command-line arguments, and argv is an array of pointers to the command-line arguments, which are null-terminated character strings. By definition, argv[argc] is a null pointer. The first element of the array (argv[0]) is the program name or an empty string.

figs/acorn.gif

An implementation is required to support at least two forms of main: one that takes no parameters, and one that takes the two parameters for command-line arguments. An implementation can support other forms of main. The standard recommends that the first two parameters should be the same as they are in the standard, and that additional parameters follow them.

figs/acorn.gif

Static objects at namespace scope can have constant or dynamic initial values, those of POD type with constant values are initialized by constant data before the program starts, and those with dynamic values are initialized by code when the program begins. When, exactly, the objects are initialized is implementation-defined. It might happen before main is called, or it might be after.

You should avoid writing code that depends on the order in which static objects are initialized. If you cannot avoid it, you can work around the problem by defining a class that performs the required initialization and defining a static instance of your class. For example, you can guarantee that the standard I/O stream objects are created early so they can be used in the constructor of a static object. See <ios> in Chapter 13 for more information and an example.

A local static object is initialized when execution first reaches its declaration. If the function is never called, or if execution never reaches the declaration, the object is never initialized.

When main returns or when exit is called (see <cstdlib> in Chapter 13), static objects are destroyed in the reverse order of their construction, and the program terminates. All local, static objects are also destroyed. If a function that contains a local, static object is called during the destruction of static objects, the behavior is undefined.

figs/acorn.gif

The value returned from main is passed to the host environment. You can return 0 or EXIT_SUCCESS (declared in <cstdlib>) to indicate success, or EXIT_FAILURE to tell the environment that the program failed. Other values are implementation-defined. Some environments ignore the value returned from main; others rely on the value.