Should programs include a prototype for main()?
Programs should never include a prototype for main.
main() is a function, mostly the same as any other function. However, main() can be defined with at least
two possible parameter lists:
int main(void)
(taking no arguments) or
int main(int argc, char** argv);
main() is a function, mostly the same as any other function. However, main() can be defined with at least
two possible parameter lists:
int main(void)
(taking no arguments) or
int main(int argc, char** argv);
NOTE
The arguments to main() don’t have to be called argc and argv, but they almost always are. There are better ways and places to be creative than making up new names for main()’s arguments.In the second case,
argc is the number of arguments passed to the program at runtime,
argv[0] is the name of the program,
argv[1] through argv[argc-1] are the arguments passed to the program, and
argv[argc] is a null pointer.
There might be other legitimate definitions, such as this one:
int main(int argc, char** argv, char** envp);
envp is an environment list, like the one used by getenv(). It’s terminated by a null pointer the same way
argv is.
There’s no prototype that can match all the legal definitions of main(). The standard says no compiler will provide a prototype for main(); in my opinion, you shouldn’t either. Without a prototype, your program can’t explicitly call main() and still do argument checking. Such a call isn’t forbidden by the standard, but it’s probably not a good idea.
NOTE
C++ programs are explicitly forbidden from calling main(). (Some compilers enable you to do this; they’re wrong.) The C++ compiler adds some magical code to main() so initialization (“construction”)
of global variables happens. If a C++ program could run main() twice, this initialization could happen twice, which would be a Bad Thing.
Cross Reference:
VIII.2: Why should I prototype a function?
No comments:
Post a Comment