Difference between exit and return

return is an instruction of the language that returns from a function call.

exit is a C library function(not a language statement) that terminates the

   current process.

   The only case when both do the same thing is in the main() function, as a 

return from main performs an exit().

Example with 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

Another example for 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


   You never get "Back from f". Also notice the #include <stdlib.h> necessary

to call the library function exit().

   It does matter. exit() immediately terminates the programtechnically

it's a return to system, no matter where it is called. return only exits the

current function. the only location they do the same thing is in main().

   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).

   The parameter of the return statement is whatever the return type of the

function is. If the the function returns void, you can omit the return at

the end of the function.

   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).

   If you return in 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.

   Last point, exit() come in two flavors _exit() and exit(). The

difference between the forms is that exit() 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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值