Why default return value of main is 0 and not EXIT

2019-01-18 02:48发布

The ISO 1998 c++ standard specifies that not explicitly using a return statement in the main is equivalent to use return 0. But what if an implementation has a different standard "no error" code, for example -1?

Why not use the standard macro EXIT_SUCCESS that would be replaced either by 0 or -1 or any other value depending on the implementation?

C++ seems to force the semantic of the program, which is not the role of a language which should only describe how the program behaves. Moreover the situation is different for the "error" return value: only EXIT_FAILURE is a standard "error" termination flag, with no explicit value, like "1" for example.

What are the reasons of these choices?

9条回答
霸刀☆藐视天下
2楼-- · 2019-01-18 03:07

0 as the return code for success, and postive integers as errors is the standard in C and Unix. This scheme was chosen because normally one doesn't care why a program succeeded, just that it did. On the other hand, there are lots of ways for a program to fail with an error, and one is often interested in this information. Hence it makes sense to use a scalar value for success, and a range of values for error. Using positive integers is a memory-saving C convention, as they allow the error code to be defined as an unsigned int.

查看更多
放荡不羁爱自由
3楼-- · 2019-01-18 03:19

Returning zero from main() does essentially the same as what you're asking. Returning zero from main() does not have to return zero to the host environment.

From the C90/C99/C++98 standard document:

If the value of status is zero or EXIT_SUCCESS, an implementation-defined form of the status successful termination is returned.

查看更多
甜甜的少女心
4楼-- · 2019-01-18 03:23

Computer language standards say what a program written in the language has to do, and what will happen. In this case, the C and C++ standards say that returning 0 signals success, among other things.

Language implementations allow programs to run on particular implementations. It's the job of the implementor to figure out how to make I/O work according to the standard, or to give the OS the correct result code.

What a program does and what the OS sees do not have to be the same thing. All that is necessary is that the program works as the standard says on the given OS.

查看更多
登录 后发表回答