C Programming Examples Tutorial Index
C Function Programs

C exit() function is a standard library function defined in the <stdlib.h> header file used to terminate C program execution immediately with an error code.

Syntax:

void exit(int status)
Parameters:
Value Description
EXIT_SUCCESS or 0 Successful
EXIT_FAILURE Unsuccessful

Use of the exit() Function in C with Example

Sometimes some situations arise during the execution of a C program where we need to end the further execution process according to the situation. For example, if a C program opens a file and that file doesn't open for some reason, it's a possible error; Here, there is no point in executing this program further. It must end with an error message by calling the exit() function. Let's see the code snippet of a practical use example to understand the exit function in C:

Example C Program:
#include <stdio.h>
#include <stdlib.h>

void main()
{
    FILE *fpointer = fopen("NotFoundFile.txt","r");
    if (fpointer == NULL)
    {
        fprintf(stderr, "File not found, failed to open it.\n");
        exit(EXIT_FAILURE);
    }
    
    /* If the file is found the code execution will continue. */
    fclose(fpointer);
    printf("Success\n");
}

Program Output:

File not found, failed to open it.