Thursday, August 28, 2008

What is wrong with using void main()? Where does the returned value from main() go?

The main() function has to return an integer value which indicates the exit status of the program. The C and C++ standards only allow declarations for main function in the below forms:

  • int main(void) { /* ... */ }

  • int main(int argc, char *argv[ ]) { /* ... */ }

Or any other form which is equivalent of the above two, such as int main() and int main(int argc, char **argv).

So, declaring it as void main() or in any other form would make your program non-standard and non-portable. Some good compilers like gcc will issue a diagnostic and fail to compile when main function is improperly declared.

Where does the returned value from main() go?
The returned value from the main() goes to the host (ie. usually your operating system) which called your program. It indicates the exit status of the program to the host. Returning 0 means the program execution was successful, and returning any other value gives implementation defined status. The macro constants EXIT_SUCCESS and EXIT_FAILURE defined in can be used to indicate the programs termination status of success and failure respectively.

In Unix-like systems, the returned value of the program is stored in a shell variable $?. So, after the execution of your program, issuing the command 'echo $?' would give you the returned value from main.

References

Please don't void my main()!
void main(void) - the Wrong Thing
comp.lang.c FAQ: Can I declare main as void, to shut off these annoying "main returns no value" messages?

0 comments: