从 main 返回零是否必要?从 main 的返回值有何用处?

发布于 2024-09-25 01:35:37 字数 390 浏览 14 评论 0原文

我知道 C89 中的约定是始终从 C 程序中的 main 返回 0 整数值,如下所示:

int main() {

    /* do something useful here */

    return 0;
}

这是向操作系统返回“成功”结果。我仍然认为自己是 C 新手(或者充其量是中级程序员),但迄今为止我从未完全理解为什么这很重要。

我的猜测是,如果您将此程序的输出绑定到另一个程序的输入中,这是一个有用的返回结果,但我不确定。我从来没有发现它有用,或者也许我只是不明白它的意图是什么。

我的问题:

  1. C 程序是否总是需要返回零?
  2. main() 的返回值有何用处?

I know it's been the convention in C89 to always return a 0 integer value from main in a C program, like this:

int main() {

    /* do something useful here */

    return 0;
}

This is to return a "successful" result to the operating system. I still consider myself a novice (or an intermediate programmer at best) in C, but to date I've never fully understood why this is important.

My guess is, this is a useful return result if you're tying the output of this program into the input of another, but I'm not sure. I've never found it useful, or maybe I just don't understand what the intention is.

My questions:

  1. Is returning zero always necessary from a C program?
  2. How is the return value from main() useful?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

风月客 2024-10-02 01:35:37

编写脚本时(例如在 Bash 中或 Windows 上的 CMD.exe 中)
您可以使用 && 链接一些命令和 ||运营商。

按照规范,a &&如果a的结果为零,并且a || b将运行b如果a返回非零,b将运行b

如果您希望在前一个命令成功的情况下有条件地运行命令,这非常有用。例如,您想删除包含单词 foo 的文件。然后你将使用:

grep foo myfile && rm myfile

当存在匹配时,grep 返回 0,否则返回非零。

When writing scripts (like in Bash, or CMD.exe on Windows)
you can chain some commands with the && and || operators.

Canonically, a && b will run b if the result of a is zero, and a || b will run b if a returned nonzero.

This is useful if you wish to conditionally run a command if the previous one succeeded. For example, you would like to delete a file if it contains word foo. Then you will use :

grep foo myfile && rm myfile

grep returns 0 when there was a match, else nonzero.

ㄖ落Θ余辉 2024-10-02 01:35:37

返回 0 是一种约定。当程序返回 0 时,可以假设它工作正常,而无需实际查看程序做了什么(咳咳:D)。

作为一种广泛使用的约定,这种假设存在于很多地方。正如 Benoit 指出的那样,shell(UNIX 和 Windows)和操作系统的其他部分就是这种情况。

所以回答你的问题:

  1. 对于 C 程序,你必须返回
    EXIT_SUCCESS 或 EXIT_FAILURE。
    但你甚至可以返回 EXIT_FAILURE
    如果你的程序运行正常。
  2. 如果你
    不要返回 0 (EXIT_SUCCESS),
    很可能其他
    程序将采用您的程序
    失败的。

有一个与 C++ 和 C 相关的问题很好的回应

main() 在 C 和 C++ 中应该返回什么?

Returning 0 is a convention. When a program returns 0, it can be assumed that it worked OK, without actually looking at what the program did (ahem :D).

As a widely used convention, that assumption is in a lot of places. As Benoit points out that's the case of the shell (UNIX and Windows) and other parts of the Operating system.

So answering your questions:

  1. For a C program you must return
    either EXIT_SUCCESS or EXIT_FAILURE.
    But you can return EXIT_FAILURE even
    if your program worked OK.
  2. If you
    don't return a 0 (EXIT_SUCCESS),
    it's quite possible that other
    programs will assume your program
    failed.

There's a related question with C++ and C great responses

What should main() return in C and C++?

笛声青案梦长安 2024-10-02 01:35:37

在现代 C 又名 C99(不确定 C89)中,main 的所有三个终止都是等效的:

  • 只是在最后一个 } 处结束 main
  • return 0
  • exit(0)

这一切背后的想法是(正如其他人提到的)向调用程序提供返回状态。

In modern C aka C99 (not sure for C89) all the three terminations of main are equivalent:

  • just ending main at the last }
  • return 0
  • exit(0)

the idea behind all this is (as others mentioned) to give a return status to the invoking program.

通知家属抬走 2024-10-02 01:35:37

返回值是程序执行的“结果”,0用于表示成功终止,而非零返回值表示失败或意外终止。

当您正常调用程序时,返回值对系统来说并不重要,但它可以有两个目的。其中之一是调试。在 MSVC(最常用的 C++ 编译器)中,您会看到程序在执行完成后返回值。这有助于了解程序退出的“方式和原因”。

另一个用途是当您的应用程序从其他程序调用时,返回值可能指示成功或传递结果。

The return value is the "result" of the program execution, and 0 is used to indicate a successful termination, while a non-zero return value indicates a failure or unexpected termination.

The return value doesn't really matter to the system when you call you program normally, but it can have two purposes. One of them is debugging. In MSVC, the most commonly used compiler for C++, you see the programs return value after it finishes executing. This can be helpful to see "how and why" your program exited.

Another use is when your application is called from other programs, where the return value may indicate success, or pass on a result.

成熟稳重的好男人 2024-10-02 01:35:37

你好,就像你说的,主要是如果该程序被用作更广泛的程序网络的一部分。将零返回到程序环境可以让网络知道一切顺利(就像你说的),但是你也可以让它返回 1、2、3...(取决于发生了什么错误)让你的代码网络知道某些事情出了问题。同样,您可以在“主”程序末尾使用 exit(0) 或 exit(1) 来执行完全相同的操作。您可能会发现这很有用:
http://en.wikipedia.org/wiki/Exit_status
希望有帮助。杰克

Hiya, like you said its mainly if the program is used as part of wider program network. Returning zero to the program environment lets the network know everything went fine (like you said) however you can also have it return 1, 2, 3... (depending on what error has occured) to let your network of code know that something has gone wrong. Equivalently, you can have exit(0) or exit(1) at the end of your 'main' program to do exactly the same thing. You may find this useful:
http://en.wikipedia.org/wiki/Exit_status
Hope that helps. Jack

把时间冻结 2024-10-02 01:35:37

当程序正确完成时,您应该使用 EXIT_SUCCESS;当程序没有正确完成时,您应该使用 EXIT_FAILURE。 EXIT_SUCCESS 为零,零可以移植到任何操作系统,而 EXIT_FAILURE 可以从 UNIX 更改为 Windows。这些常量在 stdlib.h 标头中定义。

#include <stdlib.h>

int main()
{

    int toret = EXIT_SUCCESS;

    if ( !( /* do something useful here */ ) ) {
        toret = EXIT_FAILURE;
    }

    return toret;
}

当为控制台编写程序时,程序的返回代码更有用。如今,这种情况相当罕见,除非您在非常专业的环境中工作(随着工作流程工具的出现,这种情况现在正在发生变化)。

正如@Benoit所说,退出代码告诉操作系统操作何时成功或失败。如果退出代码意味着失败,那么您可以中断批处理程序的流程,因为它不太可能成功。

例如,如果编译成功,编译器的退出代码可以为零,如果编译不成功,则可以为任何其他值。在 Windows 中,可以通过操作系统变量“errorlevel”来访问:

gcc helloworld.cpp -ohelloworld.exe
goto answer%errorlevel%
:answer0
copy helloworld.exe c:\users\username\Desktop
echo Program installed
goto end
:answer1
echo There were errors. Check your source code.
:end
echo Now exiting...

当编译成功时,此 Windows 批处理文件会在桌面上“安装”helloworld.exe。由于您可以通过双击触发批处理文件的执行,因此可以避免触摸命令行进行编译。

当然,考虑到集成环境可以更好地管理(如果退出代码不存在,它们将无法正常工作)。另请注意,ma​​ke 在该领域是最好的:

https:// en.wikipedia.org/wiki/Make_(software)

Make 也需要退出代码才能正确运行。

You should use EXIT_SUCCESS when the program finished correctly, and EXIT_FAILURE when it didn't. EXIT_SUCCESS is zero, and zero is portable to any operating system, while EXIT_FAILURE changes from UNIX to Windows, for example. These constants are defined in the stdlib.h header.

#include <stdlib.h>

int main()
{

    int toret = EXIT_SUCCESS;

    if ( !( /* do something useful here */ ) ) {
        toret = EXIT_FAILURE;
    }

    return toret;
}

The return code of the program was more useful when programs were written for the console. Nowadays, it is quite uncommon, unless you work in a very professional environment (and even this is now changing, with the workflow tools available).

As @Benoit said, the exit code tells the operating system when the operation was successful or not. If the exit code means failure, then you can break the flow of the batch program, since it is not likely to work out.

For example, a compiler can have an exit code of zero if compilation was successful, and any another value if compilation was unsuccessful. In Windows, this can be accessed through the operating system variable "errorlevel":

gcc helloworld.cpp -ohelloworld.exe
goto answer%errorlevel%
:answer0
copy helloworld.exe c:\users\username\Desktop
echo Program installed
goto end
:answer1
echo There were errors. Check your source code.
:end
echo Now exiting...

This windows batch file "installs" helloworld.exe in the Desktop when the compilation was successful. Since you can trigger execution of batch files with double-click, this can make it possible for you to avoid touching the command line for compilation.

Of course, take into account that is better managed by integrated environments (if the exit code did not exist, they wouldn't be able to work correctly). Also note that make is best in this field:

https://en.wikipedia.org/wiki/Make_(software)

Make also needs of exit codes to run correctly.

陈年往事 2024-10-02 01:35:37

我们可以从 main() 返回任何整数。
现在,如果我们没有明确提及 main() 函数返回任何特定值,则默认情况下 main() 函数返回 0。

return 0 实际上类似于程序成功终止且没有任何错误,尽管这不是规则,但这就是它的工作方式。

如果我们显式返回一个非零数字,那么即使程序运行正确,但在内部它实际上意味着程序因某些错误而终止或程序因意外结果而终止。如果根据我们当前的情况调用另一个程序,这可能会很有用程序使用“&&”返回值或“||”在我们的命令行中。

您还可以使用以下命令检查之前在 Linux 上执行的程序的返回值:

echo $?

We can return any integer from main().
Now, by default main() function returns 0 if we do not explicitly mention main() function to return any specific value.

return 0 actually resembles that the program terminated successfully without any errors though its not a rule but this is the way it works.

And if we explicitly return a non-zero number then even though the program runs correctly but internally it actually means that the program terminated with some errors or program terminated with an unexpected result.This can be useful if another program is called based on our current programs return value using '&&' or '||' in our command line.

You can also check the value of return of your previously executed program on linux using this command:

echo $?
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文