C语言 退出和返回有什么区别?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3463551/
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
What is the difference between exit and return?
提问by shona
What is difference between return and exit statement in C programming when called from anywhere in a C program?
从 C 程序中的任何位置调用时,C 编程中的 return 和 exit 语句有什么区别?
回答by kriss
- returnis an instruction of the language that returns from a function call.
- exitis a system call (not a language statement) that terminates the current process.
- return是从函数调用返回的语言指令。
- exit是终止当前进程的系统调用(不是语言语句)。
The only case when both do (nearly) the same thing is in the main()function, as a return from main performs an exit().
两者都做(几乎)相同的事情的唯一情况是在main()函数中,因为 main 的返回执行exit().
Example with return:
示例return:
#include <stdio.h>
void f(){
printf("Executing f\n");
return;
}
int main(){
f();
printf("Back from f\n");
}
If you execute this program it prints:
如果你执行这个程序,它会打印:
Executing f Back from f
Executing f Back from f
Another example for exit():
另一个例子exit():
#include <stdio.h>
#include <stdlib.h>
void f(){
printf("Executing f\n");
exit(0);
}
int main(){
f();
printf("Back from f\n");
}
If you execute this program it prints:
如果你执行这个程序,它会打印:
Executing f
Executing f
You never get "Back from f". Also notice the #include <stdlib.h>necessary to call the library function exit().
你永远不会得到“从 f 回来”。还要注意#include <stdlib.h>调用库函数的必要性exit()。
Also notice that the parameter of exit()is an integer (it's the return status of the process that the launcher process can get; the conventional usage is 0 for success or any other value for an error).
还要注意,参数 ofexit()是一个整数(它是启动程序进程可以获得的进程的返回状态;常规用法是 0 表示成功或任何其他值表示错误)。
The parameter of the return statement is whatever the return type of the function is. If the function returns void, you can omit the return at the end of the function.
return 语句的参数是函数的返回类型。如果函数返回void,则可以省略函数末尾的return。
Last point, exit()come in two flavors _exit()and exit(). The difference between the forms is that exit()(and return from main) calls functions registered using atexit()or on_exit()before really terminating the process while _exit()(from #include <unistd.h>, or its synonymous _Exit from #include <stdlib.h>) terminates the process immediately.
最后一点,exit()有两种口味_exit()和exit()。两种形式的区别在于exit()(和从 main 返回)调用使用atexit()或on_exit()在真正终止进程之前注册的函数,而_exit()(from#include <unistd.h>或其同义词 _Exit from #include <stdlib.h>)立即终止进程。
Now there are also issues that are specific to C++.
现在还有一些特定于 C++ 的问题。
C++ performs much more work than C when it is exiting from functions (return-ing). Specifically it calls destructors of local objects going out of scope. In most cases programmers won't care much of the state of a program after the processus stopped, hence it wouldn't make much difference: allocated memory will be freed, file ressource closed and so on. But it may matter if your destructor performs IOs. For instance automatic C++ OStreamlocally created won't be flushed on a call to exit and you may lose some unflushed data (on the other hand static OStreamwill be flushed).
当 C++ 从函数 ( return-ing)退出时,它执行的工作比 C 多得多。具体来说,它调用超出范围的本地对象的析构函数。在大多数情况下,程序员不会在进程停止后关心程序的状态,因此不会有太大区别:分配的内存将被释放,文件资源关闭等等。但是,如果您的析构函数执行 IO,则可能很重要。例如,OStream本地创建的自动 C++不会在调用退出时刷新,您可能会丢失一些未刷新的数据(另一方面,静态OStream将被刷新)。
This won't happen if you are using the good old C FILE*streams. These will be flushed on exit(). Actually, the rule is the same that for registered exit functions, FILE*will be flushed on all normal terminations, which includes exit(), but not calls to _exit()or abort().
如果您使用的是旧的 CFILE*流,则不会发生这种情况。这些将被刷新exit()。实际上,规则与已注册退出函数的规则相同,FILE*将在所有正常终止时刷新,包括exit()但不调用_exit()或 abort()。
You should also keep in mind that C++ provide a third way to get out of a function: throwing an exception. This way of going out of a function willcall destructor. If it is not catched anywhere in the chain of callers, the exception can go up to the main() function and terminate the process.
您还应该记住,C++ 提供了退出函数的第三种方法:抛出异常。这种退出函数的方式将调用析构函数。如果在调用者链中的任何地方都没有捕获到异常,则异常可以上升到 main() 函数并终止进程。
Destructors of static C++ objects (globals) will be called if you call either returnfrom main()or exit()anywhere in your program. They wont be called if the program is terminated using _exit()or abort(). abort()is mostly useful in debug mode with the purpose to immediately stop the program and get a stack trace (for post mortem analysis). It is usually hidden behind the assert()macro only active in debug mode.
如果您return从程序中main()或exit()在程序中的任何位置调用,则将调用静态 C++ 对象(全局)的析构函数。如果程序使用_exit()或终止,它们将不会被调用abort()。abort()在调试模式下最有用,目的是立即停止程序并获取堆栈跟踪(用于事后分析)。它通常隐藏在assert()仅在调试模式下活动的宏后面。
When is exit() useful ?
exit() 什么时候有用?
exit()means you want to immediately stops the current process. It can be of some use for error management when we encounter some kind of irrecoverable issue that won't allow for your code to do anything useful anymore. It is often handy when the control flow is complicated and error codes has to be propagated all way up. But be aware that this is bad coding practice. Silently ending the process is in most case the worse behavior and actual error management should be preferred (or in C++ using exceptions).
exit()意味着您要立即停止当前进程。当我们遇到某种无法恢复的问题时,它可以用于错误管理,这些问题不允许您的代码再做任何有用的事情。当控制流很复杂并且错误代码必须一直向上传播时,它通常很方便。但请注意,这是不好的编码习惯。在大多数情况下,悄悄地结束进程是更糟糕的行为,应该首选实际的错误管理(或在 C++ 中使用异常)。
Direct calls to exit()are especially bad if done in libraries as it will doom the library user and it should be a library user's choice to implement some kind of error recovery or not. If you want an example of why calling exit()from a library is bad, it leads for instance people to ask this question.
exit()如果在库中进行直接调用尤其糟糕,因为它会毁掉库用户,并且应该由库用户选择是否实现某种错误恢复。如果您想要一个示例来说明为什么exit()从库中调用是不好的,例如它会导致人们提出这个问题。
There is an undisputed legitimate use of exit()as the way to end a child process started by fork() on Operating Systems supporting it. Going back to the code before fork() is usually a bad idea. This is the rationale explaining why functions of the exec() family will never return to the caller.
在exit()支持它的操作系统上,有一种无可争议的合法用途作为结束由 fork() 启动的子进程的方式。回到 fork() 之前的代码通常是一个坏主意。这就是解释为什么 exec() 系列的函数永远不会返回给调用者的基本原理。
回答by hurufu
I wrote two programs:
我写了两个程序:
int main(){return 0;}
and
和
#include <stdlib.h>
int main(){exit(0)}
After executing gcc -S -O1. Here what I found watching
at assembly (only important parts):
执行后gcc -S -O1。这是我在组装时发现的(仅重要部分):
main:
movl main:
subq , %rsp /* reserving some space */
movl they are the same when used in main() function
, %edi /* setting return value */
call exit /* calling exit function */
/* magic and machine specific wizardry after this call */
, %eax /* setting return value */
ret /* return from main */
and
和
##代码##So my conclusion is: use returnwhen you can, and exit()when you need.
所以我的结论是:return在你可以的exit()时候使用,在你需要的时候使用。
回答by Dumb Guy
In C, there's not much difference when used in the startup function of the program (which can be main(), wmain(), _tmain()or the default name used by your compiler).
在C语言中,在程序的启动功能(可使用时有没有太大的区别main(),wmain(),_tmain()或你的编译器使用的默认名称)。
If you returnin main(), control goes back to the _start()function in the C library which originally started your program, which then calls exit()anyways. So it really doesn't matter which one you use.
如果您return在 中main(),控制权将返回到_start()最初启动您的程序的 C 库中的函数,然后exit()无论如何都会调用该函数。因此,您使用哪一种实际上并不重要。
回答by kapil
the return statement exits from the current function and exit() exits from the program
return 语句退出当前函数,exit() 退出程序
##代码##also return is a statement while exit() is a function which requires stdlb.h header file
return 也是一个语句,而 exit() 是一个需要 stdlb.h 头文件的函数

