What is exit() function in C language?

The exit() function in C is used to terminate a program immediately. This function causes the program to stop execution and return control to the operating system. Unlike a normal return from main(), exit() can be called from anywhere in the program.

Syntax

void exit(int status);

Parameters

  • status − An integer value returned to the operating system. Conventionally, 0 indicates successful termination, and non-zero values indicate errors.

Return Value

The exit() function does not return any value as it terminates the program immediately.

Note: To use the exit() function, you must include the <stdlib.h> header file.

Example: Basic Usage of exit() Function

The following example demonstrates how to use the exit() function in a menu-driven program −

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

int main() {
    char ch;
    
    printf("B: Breakfast<br>");
    printf("L: Lunch<br>");
    printf("D: Dinner<br>");
    printf("E: Exit<br>");
    printf("Enter your choice: ");
    
    do {
        ch = getchar();
        switch (ch) {
            case 'B':
                printf("Time for breakfast<br>");
                break;
            case 'L':
                printf("Time for lunch<br>");
                break;
            case 'D':
                printf("Time for dinner<br>");
                break;
            case 'E':
                printf("Exiting program...<br>");
                exit(0); /* return to operating system */
            default:
                if (ch != '<br>') {
                    printf("Invalid choice. Try again: ");
                }
                break;
        }
    } while (ch != 'B' && ch != 'L' && ch != 'D');
    
    return 0;
}
B: Breakfast
L: Lunch
D: Dinner
E: Exit
Enter your choice: D
Time for dinner

Key Points

  • The exit() function immediately terminates the program, regardless of where it is called.
  • Exit status 0 typically indicates successful program termination.
  • Non-zero exit status values usually indicate different types of errors.
  • Any cleanup functions registered with atexit() will be called before termination.

Conclusion

The exit() function provides a way to terminate a C program from any point in the code. It's particularly useful in error handling and menu-driven programs where immediate termination is required.

Updated on: 2026-03-15T14:14:57+05:30

9K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements