我应该从主返回EXIT_SUCCESS或0()? [英] Should I return EXIT_SUCCESS or 0 from main()?
问题描述
这是一个简单的问题,但我一直看到矛盾的答案:如果一个C ++程序返回主程序 0
或 EXIT_SUCCESS
?
It's a simple question, but I keep seeing conflicting answers: should the main routine of a C++ program return 0
or EXIT_SUCCESS
?
#include <cstdlib>
int main(){return EXIT_SUCCESS;}
或
int main(){return 0;}
他们是同样的事情?应 EXIT_SUCCESS
只能用用于出口()
?
我觉得 EXIT_SUCCESS
将是一个更好的选择,因为其他软件可能要认为零故障,但我也听说,如果返回 0
,编译器能够将其更改为不同的值反正。
I thought EXIT_SUCCESS
would be a better option because other software may want to deem zero as failure, but I also heard that if you return 0
, the compiler is capable of changing it to a different value anyway.
推荐答案
EXIT_FAILURE
,无论是在return语句主
或作为参数传递给退出()
,也是唯一可移植的方法来指示在C或C ++程序失败。 退出(1)
实际上可以在信号VMS成功的终止,例如。
EXIT_FAILURE
, either in a return statement in main
or as an argument to exit()
, is the only portable way to indicate failure in a C or C++ program. exit(1)
can actually signal successful termination on VMS, for example.
如果你打算使用 EXIT_FAILURE
当你的程序出现故障,那么你还不如用 EXIT_SUCCESS
当它成功了,只是为了对称的缘故。
If you're going to be using EXIT_FAILURE
when your program fails, then you might as well use EXIT_SUCCESS
when it succeeds, just for the sake of symmetry.
在另一方面,如果程序永远信号故障,您可以使用 0
或 EXIT_SUCCESS
。两者都通过标准保证表示成功完成。 (这是几乎没有可能的, EXIT_SUCCESS
可能比0的值,但它等于0每次我听过的执行情况。)
On the other hand, if the program never signals failure, you can use either 0
or EXIT_SUCCESS
. Both are guaranteed by the standard to signal successful completion. (It's barely possible that EXIT_SUCCESS
could have a value other than 0, but it's equal to 0 on every implementation I've ever heard of.)
使用 0
有轻微好处是你不需要的#include&LT;&stdlib.h中GT;
中C,或的#include&LT; cstdlib&GT;
在C ++中(如果您使用的是收益
语句,而不是调用退出()
) - 但你会被直接或间接反正包括STDLIB任何显著大小的程序
Using 0
has the minor advantage that you don't need #include <stdlib.h>
in C, or #include <cstdlib>
in C++ (if you're using a return
statement rather than calling exit()
) -- but for a program of any significant size you're going to be including stdlib directly or indirectly anyway.
对于这个问题,在C开始与1999年的标准,而在C ++中的所有版本,达到年底的main()
执行一个隐含的返回0;
无论如何,所以你可能不需要为使用 0
或 EXIT_SUCCESS
明确。 (但至少在C,我认为一个明确的 0的回报。
来得到更好的风格)
For that matter, in C starting with the 1999 standard, and in all versions of C++, reaching the end of main()
does an implicit return 0;
anyway, so you might not need to use either 0
or EXIT_SUCCESS
explicitly. (But at least in C, I consider an explicit return 0;
to be better style.)
这篇关于我应该从主返回EXIT_SUCCESS或0()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!