delorie.com is funded by banner ads.
  www.delorie.com/djgpp/v2faq/faq195.html   search  

| Previous | Next | Up | Top |

22.24 What should the main function return in a 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.

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.


  webmaster   donations   bookstore     delorie software   privacy  
  Copyright ⌐ 1998   by Eli Zaretskii     Updated Sep 1998  

Powered by Apache!

You can help support this site by visiting the advertisers that sponsor it! (only once each, though)