ChatGPT解决这个技术问题 Extra ChatGPT

What is the difference between exit and return?

What is difference between return and exit statement in C programming when called from anywhere in a C program?

I removed the 'close as duplicate' because the chosen duplicate is tagged with both C and C++ and there is no need to confuse people with the C++ issues (which are different from, though vaguely similar to, the C issues). The duplicate was return statement vs exit() in main()?

P
Peter Cordes

return returns from the current function; it's a language keyword like for or break.

exit() terminates the whole program, wherever you call it from. (After flushing stdio buffers and so on).

The only case when both do (nearly) the same thing is in the main() function, as a return from main performs an exit().

In most C implementations, main is a real function called by some startup code that does something like int ret = main(argc, argv); exit(ret);. The C standard guarantees that something equivalent to this happens if main returns, however the implementation handles it.

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

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 function returns void, you can omit the return at the end of the function.

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.

Now there are also issues that are specific to 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++ OStream locally created won't be flushed on a call to exit and you may lose some unflushed data (on the other hand static OStream will be flushed).

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

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 will call 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.

Destructors of static C++ objects (globals) will be called if you call either return from 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.

When is exit() useful ?

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

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.

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() is not a system call
I usually use return in main(). Certainly, I use return 0; at the end of main() — I sometimes use exit(); in the body of the function. I don't like the C99 rule about falling off the end of main() being equivalent to return 0; at the end; it was a silly special case to make (though C++ led the way first in doing the damage).
Note: the C11 standard has additional functions at_quick_exit(), _Exit() (also in C99), and quick_exit(). The _exit() function is from POSIX, but is essentially the same as _Exit().
If you wanted an example to illustrate why exit in a library is bad: it makes people ask this question stackoverflow.com/q/34043652/168175. And then presumably either use the hack or go with IPC for no good reason
@Milan: some IO are buffered, this is the cas for OStream. In that context flushed means the data was actually sent to console/written to disk and not just kept in buffer. Not flushed means the data is still in some memory buffers in the application but not yet sent to the system. In C++ docs they call the underlying system object to which data is sent a "controlled sequence". There is an explicit flush method on OStream do do that.
h
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):

main:
    movl    $0, %eax    /* setting return value */
    ret                 /* return from main */

and

main:
    subq    $8, %rsp    /* reserving some space */
    movl    $0, %edi    /* setting return value */
    call    exit        /* calling exit function */
                        /* magic and machine specific wizardry after this call */

So my conclusion is: use return when you can, and exit() when you need.


This is a very good answer except for the conclusion; IMHO it motivates the opposite one: we can assume that the ret instruction returns to a point where there is maybe some additional work done, but in the very end the exit() function will be called anyway - or how could be avoided to do whatever exit() does? Which means the former does just some additional "duplicate" work without any benefit over the second solution, given that exit() is most certainly called in the very end, anyway.
@Max: it is not forbidden to recursively call main from your own program. Henceforth you should not assume that returning from main will immediately exit, this would break code semantic. In some (rare) cases it's even usefull. For instance to help prepare/clear some context before calling main after changing code entry-point to something different from main. This could even be done by some run-time code injection method. Of course when it's your program do whatever you prefer or believe is easier to read.
@kriss: this is an excellent point which hasn't been mentioned earlier. Although I think it's extremely rare that main() is called recursively, this possibility clarifies IMHO better than anything else the difference between return and exit(0).
D
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).

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.


It does matter. exit() immediately terminates the program, no matter where it is called. return only exits the current function. the only location they do the same thing is in main()
Thanks, i have fixed the wording. It is not necessarily only in main(), as not all compilers use the same function name for the startup function.
I guess you write all your programs in one big main function? ;-)
Answer is not complete but still informative.
k
kapil

the return statement exits from the current function and exit() exits from the program

they are the same when used in main() function

also return is a statement while exit() is a function which requires stdlb.h header file


They're the same if main is called by any any of the functions in your program. That's rare; most programs don't use a recursive or re-entrant main, but if we're talking about language details then that's a possibility.
J
Jonathan Leffler

For the most part, there is no difference in a C program between using return and calling exit() to terminate main().

The time when there is a difference is if you've created code that will be executed after you return from main() that relies on variables local to main(). One way that manifests itself is with setvbuf():

int main(void)
{
    char buffer[BUFSIZ];
    setvbuf(stdout, buffer, _IOFBF, BUFSIZ);
    …code using stdout…
    return 0;
}

In this example, the buffer provided via setvbuf() goes out of scope when main() returns, but the code that flushes and closes stdout will be attempting to use that buffer. This leads to undefined behaviour.

The other mechanism is to invoke atexit() with a function that accesses data from main() — via a pointer. This is harder to set up as the functions called via the atexit() mechanism are not given any arguments. So, you have to do something like this:

static void *at_exit_data = 0;

static void at_exit_handler(void)
{
    char *str = at_exit_data;
    printf("Exiting: %s\n", str);
}

int main(void);
{
    char buffer[] = "Message to be printed via functions registered with at_exit()";
    at_exit_data = buffer;
    at_exit(at_exit_handler);
    …processing…
    return 0;
}

Again, the buffer pointed at by at_exit_data has ceased to exist when the program returned from main() and so the handler function invokes undefined behaviour.

There is a related function, at_quick_exit(), but the functions registered with it are only called if the quick_exit() function is called, which precludes the functions being called after main() returns.