在 C++ 程序的 main 函数中,`return 0` 是什么意思?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8696698/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
In the main function of a C++ program, what does `return 0` do and mean?
提问by Johnsyweb
Possible Duplicate:
What is the proper declaration of main?
可能的重复:
main 的正确声明是什么?
Without citing any code in particular, I am looking for an explanation of the below example:
没有特别引用任何代码,我正在寻找对以下示例的解释:
#include <iostream>
int main()
{
std::cout << "Hello world" << std::endl;
return 0;
}
I don't understand what return 0
does. Can you please explain this in as plain English as possible?
我不明白有什么return 0
作用。你能用尽可能简单的英语解释一下吗?
回答by Johnsyweb
This defines the exit statusof the process. Despite being an int
, on Unix-like systems, the value is always in the range 0-255 (see Exit and Exit Status). On Microsoft systems you may use 32-bit signed integers as exit codes, which you can check with %ERRORLEVEL%
. For portability, I'd recommend sticking to the 0-255 range.
这定义了进程的退出状态。尽管是int
,在类 Unix 系统上,该值始终在 0-255 范围内(请参阅退出和退出状态)。在 Microsoft 系统上,您可以使用32 位有符号整数作为退出代码,您可以使用%ERRORLEVEL%
. 为了便携性,我建议坚持 0-255 范围。
Here is a trivial example:
这是一个简单的例子:
$ cat -n exit_code.cpp
1 int main()
2 {
3 return 42;
4 }
5
Build:
建造:
$ make exit_code
g++ exit_code.cpp -o exit_code
Run (in bash):
运行(在 bash 中):
$ ./exit_code
Check the exit status:
检查退出状态:
$ echo $?
42
Conventionally, a status of zero signifies success and non-zero failure. This can be useful in shell scripts, and so forth to indicate the level of failure, if any:
通常,状态为零表示成功和非零失败。这在 shell 脚本等中很有用,以指示故障级别(如果有):
$ ./exit_code
exit_status=$?
if [[ ${exit_status} ]] ; then
echo "The process failed with status ${exit_status}."
else
echo "Success!"
fi
The process failed with status 42.
Following the comments below...
按照下面的评论...
In the standard C++header <cstdlib>
, the following macros are defined:
在标准C++头文件中<cstdlib>
,定义了以下宏:
#define EXIT_SUCCESS 0
#define EXIT_FAILURE 1
However, the Exit Statussection of the GNU CLibrary documentation, describing the same macros, sagely states:
但是,GNU C库文档的退出状态部分描述了相同的宏,明智地指出:
Portability note: Some non-POSIX systems use different conventions for exit status values. For greater portability, you can use the macros EXIT_SUCCESS and EXIT_FAILURE for the conventional status value for success and failure, respectively. They are declared in the file stdlib.h.
可移植性说明:一些非 POSIX 系统对退出状态值使用不同的约定。为了获得更大的可移植性,您可以分别使用宏 EXIT_SUCCESS 和 EXIT_FAILURE 作为成功和失败的常规状态值。它们在文件 stdlib.h 中声明。
回答by Lightness Races in Orbit
General return
ing
一般return
ING
Every function has a return type.
每个函数都有一个返回类型。
In the below example, the type is void
, which is an "incomplete type" with no values; using this as the return type means that the function returns no value:
在下面的例子中,类型是void
,这是一个没有值的“不完整类型”;使用 this 作为返回类型意味着该函数不返回任何值:
void foo() {
std::cout << "Hello world\n";
}
However, in the below example, the return type is int
:
但是,在下面的示例中,返回类型是int
:
int foo() {
return 3;
}
The return
statement determines what value calls to function foo
will evaluate to. So, std::cout << foo()
will result in "3
" being printed to standard output.
该return
语句确定对函数的调用foo
将评估为什么值。因此,std::cout << foo()
将导致“ 3
”被打印到标准输出。
return
ing from main
, specifically
return
来自main
,特别是
When the function in question happens to be the "main" function, or the program's entrypoint, it's a bit more special, because the "return value" of the "main" function is taken to be the program's "exit code" — it tells the calling environment (e.g. terminal session) whether the program's execution was deemed to be successful. It must be an int
, and a value of 0
here means "everything went fine":
当有问题的函数恰好是“main”函数或程序的入口点时,它有点特殊,因为“main”函数的“返回值”被认为是程序的“退出代码”——它告诉调用环境(例如终端会话)程序的执行是否被认为是成功的。它必须是一个int
,0
这里的值意味着“一切顺利”:
It's worth noting that you can actually completely omit return 0;
in the "main" functionas it will be included implicitly. This doesn't help you much, though, if you want to return 1;
or some other value, and it doesn't come into play with other functions.
值得注意的是,您实际上可以return 0;
在“main”函数中完全省略,因为它将被隐式包含。但是,如果您想要return 1;
或其他一些价值,这对您没有多大帮助,并且它不会与其他功能一起发挥作用。
Citations
引文
[C++11: 3.6.1/5]:
A return statement inmain
has the effect of leaving the main function(destroying any objects with automatic storage duration) and callingstd::exit
with the return value as the argument.If control reaches the end ofmain
without encountering a return statement, the effect is that of executingreturn 0;
[C++11: 3.6.1/5]:
中的 return 语句main
具有离开主函数(销毁任何具有自动存储持续时间的对象)并std::exit
以返回值作为参数调用的效果。如果控制到达结束而main
没有遇到 return 语句,效果就是执行return 0;
[C++11: 18.5/8]:
[[noreturn]] void exit(int status)
The function
exit()
has additional behaviorin this International Standard:
- First, objects with thread storage duration and associated with the current thread are destroyed.
Next, objects with static storage duration are destroyed and functions registered by callingatexit
are called. See 3.6.3 for the order of destructions and calls. (Automatic objects are not destroyed as a result of calling exit().)
If control leaves a registered function called by exit because the function does not provide a handler for a thrown exception,terminate()
shall be called (15.5.1).- Next, all open C streams (as mediated by the function signatures declared in
<cstdio>
) with unwritten buffered data are flushed, all open C streams are closed, and all files created by callingtmpfile()
are removed.- Finally, control is returned to the host environment. If status is zero or
EXIT_SUCCESS
, an implementation-defined form of the status successful termination is returned. If status isEXIT_FAILURE
, an implementation-defined form of the status unsuccessful termination is returned. Otherwise the status returned is implementation-defined.
[C++11: 18.5/8]:
[[noreturn]] void exit(int status)
该函数
exit()
在本国际标准中具有附加行为:
- 首先,销毁具有线程存储持续时间并与当前线程相关联的对象。
接下来,具有静态存储期的对象被销毁,并调用通过调用注册的函数atexit
。销毁和调用的顺序见 3.6.3。(自动对象不会因调用 exit() 而被销毁。)
如果控制离开了由 exit 调用的注册函数,因为该函数没有为抛出的异常提供处理程序,terminate()
则应调用 (15.5.1)。- 接下来,所有
<cstdio>
具有未写入缓冲数据的打开 C 流(由 中声明的函数签名介导)被刷新,所有打开的 C 流都被关闭,并且所有通过调用创建的文件tmpfile()
都被删除。- 最后,控制权返回给宿主环境。如果 status 为零或
EXIT_SUCCESS
,则返回状态成功终止的实现定义形式。如果 status 是EXIT_FAILURE
,则返回状态不成功终止的实现定义形式。否则返回的状态是实现定义的。
引导笔记
I suggest one of these resources, as this sort of thing is explained properly in any decent peer-reviewed C++ book; YouTube tutorials are not a good way to learn C++, and Stack Overflow contributors will generally expect you to have a decent book to form your prior research before resorting to asking for help.
我建议使用这些资源之一,因为在任何体面的同行评审 C++ 书中都正确解释了这种事情;YouTube 教程并不是学习 C++ 的好方法,Stack Overflow 的贡献者通常希望您在寻求帮助之前有一本像样的书来形成您先前的研究。
回答by Manlio
It's used because you may use your program as a command line tool. If there is another process waiting for the output of your program you may choose to return 0 if everything is successful, -1 if there was an error or any other constant, according to what you want to communicate.
使用它是因为您可以将您的程序用作命令行工具。如果有另一个进程在等待您的程序的输出,您可以选择在一切成功时返回 0,如果有错误或任何其他常量,则根据您要通信的内容选择返回 -1。
回答by David Titarenco
Think of your boss telling you to go pick up the mail. After you pick up the mail, you tell your boss that everything went okay.
想想你的老板告诉你去取邮件。收到邮件后,你告诉老板一切顺利。
The operating system is the boss, the program is you. And all return 0
does is tells the operating system that everything went okay.
操作系统是老板,程序是你。和所有return 0
做的是告诉操作系统是一切正常。
回答by marcinj
Under windows you can test for return value as follows (in batch script):
在 Windows 下,您可以按如下方式测试返回值(在批处理脚本中):
MyAppTest.exe
@if "%ERRORLEVEL%" == "0" goto success
echo Failure
goto end
:success
echo Success
:end
回答by Ben Voigt
Returning from main()
has the same effect as calling std::exit()
and passing the return value as the status
parameter.
返回与main()
调用std::exit()
和传递返回值作为status
参数具有相同的效果。
The behavior of std::exit
is detailed in section 18.5 ([support.start.term]
), and describes the status code:
的行为std::exit
在 18.5 ( [support.start.term]
)节中有详细说明,并描述了状态代码:
Finally, control is returned to the host environment. If status is zero or
EXIT_SUCCESS
, an implementation-defined form of the status successful termination is returned. If status isEXIT_FAILURE
, an implementation-defined form of the status unsuccessful termination is returned. Otherwise the status returned is implementation-defined.
最后,控制权返回给宿主环境。如果 status 为零或
EXIT_SUCCESS
,则返回状态成功终止的实现定义形式。如果 status 是EXIT_FAILURE
,则返回状态不成功终止的实现定义形式。否则返回的状态是实现定义的。
回答by Frunsi
On a modern operating system, every program will exit with a specific "exit code".
在现代操作系统上,每个程序都会以特定的“退出代码”退出。
DISCLAIMER NO 1.: The actual specification of that concept (of having an exit code at all) is out of the scope of any programming language specification at all. So: ANYONE asking me again about a reference to a standard may please retreat into itself, and think about a better answer for the moment.
免责声明 1:该概念的实际规范(完全具有退出代码)根本超出了任何编程语言规范的范围。所以:任何人再次向我询问对标准的引用时,请先回想一下,暂时考虑一个更好的答案。
DISPLAIMER NO 2.: The actual values of those exit codes are not specified in not actual "programming language specification", because that is out of the scope of a "programming language specification".
DISPLAIMER NO 2.:这些退出代码的实际值没有在非实际的“编程语言规范”中指定,因为这超出了“编程语言规范”的范围。
So long, practice has shown, that an exit code of "0" means "success", and any other code signals an error...
长期以来,实践表明,退出代码“0”表示“成功”,任何其他代码都表示错误......
回答by user1056635
0
is an integer.
0
是一个整数。
Your main function has to return an integer.
您的主函数必须返回一个整数。
Just look at:
看看:
int main()
int
stands for integer and return
in this case, returns 0
: an integer to terminate the program.
int
代表整数,return
在这种情况下,返回0
:一个整数来终止程序。
Usually for an error you have to return 1
; 0
is the conventional value for success.
通常对于错误,您必须返回1
;0
是成功的传统价值。
回答by Serodis
return is used to escape the function. Returning the value 0 simply allows it to exit with a code: 0. Also, returning with 0 claims a successful exit of the application.
return 用于转义函数。返回值 0 只是允许它以代码退出:0。此外,返回 0 表示应用程序成功退出。
回答by ???
Depends on operating system, but an exit code of 0 means success on UNIX, VMS and Windows
取决于操作系统,但退出代码 0 表示在 UNIX、VMS 和 Windows 上成功