Possible Duplicate:
What should main() return in C/C++?
Difference between void main and int main?
I have always been using the main method in C like
void main(){ // my code }
and it works pretty well for me.
I also know about the other int return type:
int main(void)
int main()
int main(int argc, char *argv[])
But I have not been able to find any resource that says that I can use void as a return type. Every book suggests that the return type must be int or else it be omitted. Then why does void main() work?
Is this dependent on the version of C that I am using? Or does it work because I use a C++ IDE? Please reply specific to C and not C++.
Only book authors seem to be privy to the place where a return type of
voidformain()is allowed. The C++ standard forbids it completely.The C standard says that the standard forms are:
and
allowing alternative but equivalent forms of declaration for the argument types (and the names are completely discretionary, of course, since they’re local variables to the function).
The C standard does make small provision for ‘in some other implementation defined manner’. The ISO/IEC 9899:2011 standard says:
This clearly allows for non-
intreturns, but makes it clear that it is not specified. So,voidmight be allowed as the return type ofmain()by some implementation, but you can only find that from the documentation.(Although I’m quoting C2011 standard, essentially the same words were in C99, and I believe C89 though my text for that is at the office and I’m not.)
Incidentally, Appendix J of the standard mentions:
Why does
void main()work?The question observes that
void main()works. It ‘works’ because the compiler does its best to generate code for programs. Compilers such as GCC will warn about non-standard forms formain(), but will process them. The linker isn’t too worried about the return type; it simply needs a symbolmain(or possibly_main, depending on the system) and when it finds it, links it into the executable. The start-up code assumes thatmainhas been defined in the standard manner. Ifmain()returns to the startup code, it collects the returned value as if the function returned anint, but that value is likely to be garbage. So, it sort of seems to work as long as you don’t look for the exit status of your program.