exit() in C - Source Code Example

In this source code example, we will see how to use the exit() function in C programming with an example.

exit() Function Overview

The exit() function is a standard C library function found in <stdlib.h>. It provides a method to terminate a program's execution and return control to the operating system. 

The exit() function also returns a status code, with 0 typically indicating successful execution and non-zero values indicating various error states.

Source Code Example

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

void endFunction() {
    printf("This function is called before the program ends.\n");
}

int main() {
    // Registering endFunction to be called on program exit
    atexit(endFunction);

    printf("Starting the program...\n");

    // Normal program exit with success status
    if (1) {
        printf("Program exiting normally.\n");
        exit(0); // Successful termination
    }

    // This code will never be executed due to the above exit
    printf("This won't be printed.\n");

    return 0;
}

Output

Starting the program...
Program exiting normally.
This function is called before the program ends.

Explanation

1. At the beginning of the main() function, we register a function named endFunction to be executed when the program ends using the atexit() function. This demonstrates that functions registered with atexit() are called even when exit() is used to terminate the program.

2. We then print a starting message.

3. Next, the program checks a condition (which is always true in this case) and enters the if block. Within this block, a message is printed, and the program terminates using the exit(0) function.

4. Any code after the exit() call within the same function is unreachable and will not be executed. In our example, the "This won't be printed." message demonstrates this.

5. Finally, before the program fully terminates, the endFunction is executed, printing its message.


Comments