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
or - The constant EXIT_FAILURE defined in
or
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.
Note: Some operating systems, such as Unix, MS-DOS, and Windows, truncate the integer passed to exit() or returned from main() to an unsigned char and make this available to the shell script, batch file, or parent process which invoked the program. On these systems programmers sometimes use different positive numbers to indicate different reasons for the failure of the program to execute successfully. Such usage is not portable and may not work correctly on all implementations and operating systems. Only the values 0 and the constants EXIT_SUCCESS and EXIT_FAILURE are portable and guaranteed to work correctly on all hosted implementations.
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.
ไม่มีความคิดเห็น:
แสดงความคิดเห็น