The exit function is used to terminate the execution of a program, generally in the case of failure. Different from abort, exit guarantees that some resources, such as files and streams, will be cleaned up.

The exit function has one parameter, which is sent to the operating system to represent the status of the program. Two constants are predefined for this use: EXIT_SUCCESS and EXIT_FAILURE.

The exit function performs a number of tasks before it ends the program, including: calling all functions registered by atexit, close all files open by the program, and flush all input/output streams.

The following code shows an example of exit in use:

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

int main()
        int i;
        scanf("%d", &i);
        if (i < 0) {
                exit(EXIT_FAILURE); // this is an "unrecoverable" error
        exit(EXIT_SUCCESS); // this is a "normal" exit
        return 0;
Article created on 2008-08-19 21:50:37

Post a comment