Difference between “return 0” and “exit (0)” [dupl

2020-05-14 09:57发布

Is there any difference between return 0 and exit (0) when using in a function? If yes, When should I use return 0 or exit (0) in a function?

标签: c function
4条回答
戒情不戒烟
2楼-- · 2020-05-14 10:35
  • return is a statement that returns control back to the calling function.
  • exit is a system call which terminates the current process i.e the currently executing program.

In main() the return 0; and exit(0); perform the same thing.

NOTE: you have to include #include<stdlib.h>.

查看更多
迷人小祖宗
3楼-- · 2020-05-14 10:38

return exits from the function while exit exits from the program.

In main function executing return 0; statement or calling exit(0) function will call the registered atexit handlers and will cause program termination.

查看更多
▲ chillily
4楼-- · 2020-05-14 10:44

Yes there is, since there is no statement called exit. I guess you mean the function exit?

In that case, there is a big difference: The exit function exits the process, in other words the program is terminated. The return statement simply return from the current function.

They are only similar if used in the main function.

查看更多
Root(大扎)
5楼-- · 2020-05-14 10:52

exit 0 is a syntax error in C. You can have exit(0) that is instead a call to a standard library function.

The function exit will quit the whole program, returning the provided exit code to the OS. The return statement instead only quits the current function giving the caller the specified result.

They are the same only when used in main (because quitting the main function will terminate the program).

Normally exit is only used in emergency cases where you want to terminate the program because there's no sensible way to continue execution. For example:

//
// Ensure allocation of `size` bytes (will never return
// a NULL pointer to the caller).
//
// Too good to be true? Here's the catch: in case of memory
// exhaustion the function will not return **at all** :-)
//
void *safe_malloc(int size) {
    void *p = malloc(size);
    if (!p) {
        fprintf(stderr, "Out of memory: quitting\n");
        exit(1);
    }
    return p;
}

In this case if function a calls function b that calls function c that calls safe_malloc you may want to quit the program on the spot instead of returning to c an error code (e.g. a NULL pointer) if the code is not written to handle allocation failures.

查看更多
登录 后发表回答