Difference between exit() and return in C

1. Introduction

In C programming, exit() and return are two mechanisms used to terminate a function or a program, but they serve different purposes and behave differently. Understanding their differences is important for proper program control flow and memory management.

2. Key Points

1. exit() is a standard library function that terminates the entire program.

2. return is a statement that exits the current function and returns control to the calling function.

3. exit() can be called from anywhere in the program.

4. return is used at the end of a function to return a value or terminate the function.

3. Differences

exit() return
Terminates the entire program. Terminates the current function.
Can be called from any function. Used at the end of a function to return control to the caller.
Does not return to the calling function. Returns to the calling function (can return a value in case of non-void functions).

4. Example

#include <stdio.h>
#include <stdlib.h>

// Function using return
int sum(int a, int b) {
    return a + b;

int main() {
    int result = sum(5, 7);
    printf("Sum: %d\n", result);

    printf("Exiting program with exit()\n");

    // This line will not be executed
    printf("This will not be printed\n");

    return 0; // This line will not be reached


Sum: 12
Exiting program with exit()


1. The sum function uses return to send the result back to main.

2. In main, after printing the sum, exit(0) is called, which terminates the program. The statements following exit(0) are not executed.

5. When to use?

- Use return in functions to send a value back to the caller or to indicate that the function has completed its execution.

- Use exit() to immediately terminate the program, such as in situations where continuing execution is undesirable or in case of a critical error.

Related C Programming Posts:

Difference between malloc() and calloc()?

Difference between Local Variable and Global Variable in C

Difference between Global and Static Variables in C

Difference Between Call by Value and Call by Reference in C

Difference Between getch() and getche() in C

Difference between printf() and sprintf() in C

Difference between Arrays and Pointers in C

Difference between Structure and Union in C

Difference Between Stack and Heap Memory Allocation in C

Difference Between Macro and Function in C

Difference between = and == in C

Difference Between for loop and while loop in C

Difference Between Linked List and Array in C

Difference between fgets() and gets() in C

Difference between ++i and i++ in C

Difference between struct and typedef struct in C

Difference between int main() and void main() in C

Difference between Character Array and String in C

Difference between break and continue in C

Difference between exit() and return in C