The main Function

Summary: Every C program must have one and only one main function.

Every C program must have a function named main, which tells where program execution begins and ends. Although main is not a C keyword, it has only one use: naming the main function. A program must have only one main function, and you shouldn't use the name anywhere else.

Below is the simplest possible C program:

main()

{

}

The braces ({ }) mark the main function's beginning and end, as they do in every function. This program doesn't contain any executable statements; it simply begins and ends.

Most functions have executable statements, of course, and these appear within the function's braces. The following program contains a statement which prints Hello, world! on the screen:

main()

{

printf( "Hello, world!\n" );

}

The main function is called by the operating system when it runs your program. While it's possible to call the main function in a program, you should never do so, just as you wouldn't write a QuickBasic program containing the line

10 GOSUB 10

A program that calls main will start again and again in an endless loop that eventually triggers a run-time error.

Like all functions, main can accept arguments and return a value. Through this mechanism, your program can receive command-line arguments from DOS when it begins execution and return a value to DOS when it ends. For more information on how to receive command-line arguments via main, see topic .