exit() vs _Exit() function in C and C++

In C, both exit() and _Exit() functions terminate a program, but they differ in how they handle cleanup operations. The exit() function performs cleanup operations before termination, while _Exit() terminates immediately without any cleanup.

Syntax

void exit(int status);
void _Exit(int status);

The exit() function calls registered cleanup functions (via atexit()), flushes buffers, and closes open streams before termination. The _Exit() function immediately terminates the program without performing any cleanup operations.

Example 1: Using exit() Function

Here's how exit() executes cleanup functions registered with atexit()

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

void my_cleanup_function(void) {
    printf("Cleanup function executed before exit\n");
}

int main() {
    atexit(my_cleanup_function);
    printf("About to call exit()\n");
    exit(0);
    printf("This line will never execute\n");
    return 0;
}

Output

About to call exit()
Cleanup function executed before exit

Example 2: Using _Exit() Function

The _Exit() function bypasses all cleanup operations −

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

void my_cleanup_function(void) {
    printf("Cleanup function executed before exit\n");
}

int main() {
    atexit(my_cleanup_function);
    printf("About to call _Exit()\n");
    _Exit(0);
    printf("This line will never execute\n");
    return 0;
}

Output

About to call _Exit()

Comparison

Feature exit() _Exit()
Cleanup Functions Executes atexit() functions Skips all cleanup
Buffer Flushing Flushes all open streams No buffer flushing
File Closing Closes open files Files remain open
Speed Slower due to cleanup Faster termination

Key Points

  • Use exit() for normal program termination where cleanup is required
  • Use _Exit() when immediate termination is needed without cleanup
  • Both functions accept an integer status code that is returned to the operating system
  • Code after either function call will never execute

Conclusion

The exit() function provides safe program termination with proper cleanup, while _Exit() offers immediate termination without cleanup. Choose exit() for normal termination and _Exit() only when cleanup operations should be avoided.

Updated on: 2026-03-15T10:11:16+05:30

545 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements