0
0
CConceptBeginner · 3 min read

What is exit function in C: Explanation and Example

The exit function in C immediately stops the program and returns a status code to the operating system. It is used to end a program at any point, cleaning up resources before closing.
⚙️

How It Works

The exit function in C is like pressing a stop button on your program. When called, it ends the program right away, no matter where you are in the code. It also sends a number back to the system to say if the program finished successfully or if there was an error.

Think of it like finishing a task and telling your boss if everything went well or if something went wrong. The exit function also makes sure to clean up things like closing files or flushing output buffers before the program stops, so nothing is left hanging.

💻

Example

This example shows how to use exit to stop a program early if a condition is met.

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

int main() {
    int number = 5;
    if (number < 10) {
        printf("Number is less than 10, exiting now.\n");
        exit(1);  // Exit with status 1 indicating a special condition
    }
    printf("This line will not run if exit is called.\n");
    return 0;
}
Output
Number is less than 10, exiting now.
🎯

When to Use

Use exit when you want to stop the program immediately, such as when an error happens or a required condition is not met. For example, if a file cannot be opened or user input is invalid, calling exit ends the program cleanly.

This helps avoid running code that depends on something that failed, and it lets the system know the program ended with an error or special status by the number you give exit.

Key Points

  • exit stops the program immediately.
  • It sends a status code to the operating system.
  • It cleans up resources like open files and flushes output buffers.
  • Use it to handle errors or special conditions.
  • Common status codes: 0 means success, non-zero means error.

Key Takeaways

The exit function immediately ends a C program and returns a status code.
Use exit to stop the program when an error or special condition occurs.
Exit cleans up resources before closing the program.
A status code of 0 means success; non-zero means an error or special exit.
Exit can be called from anywhere in the program to stop execution.