Why int main( ) ? but not void main( ) ?
The ANSI/ISO standards for C and C++ define the languages.
ANSI's International Standard For C
The function called at program startup is named main.
The implementation declares no prototype for this function. It can be defined with no parameters:
int main(void) { /* ... */ }
or with two parameters (referred to here as argc and argv, though any names may be used, as they are local to the function in which they are declared):
int main(int argc, char *argv[ ]) { /* ... */ }
This function shall not be overloaded.
It should have a return type of type int.
Practical Reasons To Return An int from main()
On many operating systems, the value returned by main() is used to return an exit status to the environment. On Unix, MS-DOS, and Windows systems, the low eight bits of the value returned by main() is passed to the command shell or calling program. This is often used to change the course of a program, batch file, or shell script.
Many compilers will refuse to compile a source code file containing a definition of main() which does not return an int.
On some platforms a program starting with void main() may crash on startup, or when it ends.
A program which contains a main() function that is not defined to return an int is just plain not real C or C++..
What should my "int main()" return?
As pointed out in the section above, it is extremely common for a program to return a result indication to the operating system. Some operating systems require a result code. And the return value from main(), or the equivalent value passed in a call to the exit() function, is translated by your compiler into an appropriate code.
There are three and only three completely standard and portable values to return from main() or pass to exit():
The plain old ordinary integer value 0.
The constant EXIT_SUCCESS defined in .
If you use 0 or EXIT_SUCCESS your compiler's run time library is guaranteed to translate this into a result code which your operating system considers as successful.
If you use EXIT_FAILURE your compiler's run time library is guaranteed to translate this into a result code which your operating system considers as unsuccessful.
C++ Note
In a C++ program you do not have to return anything from int main()! The language standard guarantees that if your int main() function "falls off the end" by reaching the closing brace, the compiler will automatically return 0 for you indicating success.
Warnings
It is not good programming practice to take advantage of this C++ feature. Programs should always specifically indicate a return status.
C++ does not provide this automatic return for any function except int main().
C does not provide an automatic return value for main() or any other function. It is up to the program to specify a return value or the status returned to the operating system is undefined.

0 Comments:
Post a Comment
Subscribe to Post Comments [Atom]
<< Home