mainfunction return in a C/C++ program?
Q: Why does everybody tell me that
void main is bad?
void main is incorrect, how come the compiler lets it
A: The ANSI/ISO C Standard specifies that the
function be declared in one of the following two ways:
int main (void);
int main (int argc, char **argv);
In both cases the return type is an
int, and your
function should therefore either return an
int or call the
exit, when the program ends. The C++
standard includes a similar requirements for C++ programs.
Since the runtime environment assumes that
main returns an
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
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,
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.
|webmaster||delorie software privacy|
|Copyright © 2001 by Eli Zaretskii||Updated Apr 2001|