Node:void main, Next:, Previous:Lexicon, Up:Miscellany

22.25 What should the main function return in a C/C++ program?

Q: Why does everybody tell me that void main is bad?

Q: If void main is incorrect, how come the compiler lets it compile?

A: The ANSI/ISO C Standard specifies that the main function be declared in one of the following two ways:

 int main (void);

or

 int main (int argc, char **argv);

In both cases the return type is an int, and your main function should therefore either return an int or call the library function exit, when the program ends. The C++ standard includes a similar requirements for C++ programs.

Since the runtime environment assumes that main returns an int, declaring main with any other return type, including void, invites trouble. The compiler might compile such a program, since the ANSI Standard doesn't require it to fail, but the behavior of such a program is, in the Standard's parlance, "undefined" (read: anything can happen). That is why GCC will print a warning in these cases if you use the -Wall switch.

To summarize, using void main is unsafe and can potentially do evil things to your program. It is best to avoid it.

Note that the C++ standard, in contrast to the C standard, explicitly prohibits void main(), and explicitly says that if the controls reaches the end of main without encountering a return statement, the effect is that of executing return 0;. When compiling a C++ program, GCC automatically generates the code to return zero from the main function, in case the programmer leaves that out.