28

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?

6

4 Answers 4

31

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.

1
  • 17
    The atexit handlers get called when returning from main, too.
    – Carl Norum
    Jun 29, 2013 at 17:47
12

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.

8

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.

0
  • 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>.

1
  • 3
    "Some compilers even accept and compile the code even if u dont write return 0" because it's standard.
    – effeffe
    Jun 29, 2013 at 17:55

Not the answer you're looking for? Browse other questions tagged or ask your own question.