在C ++程序的主函数中,`return 0`是什么意思? [英] In the main function of a C++ program, what does `return 0` do and mean?

查看:401
本文介绍了在C ++程序的主函数中,`return 0`是什么意思?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

Possible Duplicate:
What is the proper declaration of 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;
}



我不明白 code>。

I don't understand what return 0 does. Can you please explain this in as plain English as possible?

推荐答案

这定义了退出状态。尽管是一个 int ,在类Unix系统上,该值总是在0-255之间(见退出和退出状态)。在Microsoft系统上,您可以使用 32位有符号整数作为退出代码,您可以请检查%ERRORLEVEL%。对于可移植性,我建议坚持0-255范围。

This defines the exit status of 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.

这里是一个小例子:

$ 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

运行(在bash中):

Run (in bash):

$ ./exit_code

检查退出状态:

$ echo $?
42

常规,零状态表示成功非零故障。这在shell脚本中是有用的,以此来指示失败的级别,如果有的话:

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:

$ ./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...

在标准 C ++ 标头< cstdlib> ,定义了以下宏:

In the standard C++ header <cstdlib>, the following macros are defined:

#define EXIT_SUCCESS 0
#define EXIT_FAILURE 1

但是, GNU C 库文档的退出状态部分>描述相同的宏,sagely陈述:

However, the Exit Status section of the GNU C Library documentation, describing the same macros, sagely states:


可移植性注释:一些非POSIX系统对退出状态值使用不同的约定。为了更好的可移植性,可以分别使用宏EXIT_SUCCESS和EXIT_FAILURE作为常规状态值的成功和失败。它们在文件stdlib.h中声明。

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.

这篇关于在C ++程序的主函数中,`return 0`是什么意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆