C Function Exit
## C Library Function β exit()
The `exit()` function is used to terminate the current program and return a status code.
### Header File
```c
#include
```
### Function Definition
```c
void exit(int status);
```
### Parameters
| Parameter | Description |
|-----------|-------------|
| `status` | The exit status of the program. Typically, `EXIT_SUCCESS` is used to indicate success, and `EXIT_FAILURE` is used to indicate failure. |
### Return Value
This function does not return any value.
### Example
The following example demonstrates how to use the `exit()` function:
```c
#include
#include
int main()
{
FILE *fp;
fp = fopen("file.txt", "r");
if( fp == NULL )
{
perror("Error opening file");
exit(EXIT_FAILURE);
}
fclose(fp);
return 0;
}
```
### Output
If the `file.txt` file does not exist, the program will output the following:
```
Error opening file: No such file or directory
```
Then the program terminates.
### Notes
- The `exit()` function immediately terminates the program and executes all registered cleanup functions (such as those registered with `atexit()`).
- It closes all open file streams and returns control to the operating system.
- When using `exit()`, ensure that necessary resource release and cleanup work is completed before calling it.
- If the program ends normally, it is recommended to use `return 0;`; if terminating prematurely due to an error, it is recommended to use `exit(EXIT_FAILURE);`.
> **Note:** Do not confuse with `return`. `return` only returns from the current function, while `exit()` terminates the entire program.
---
[Previous: abort()](#) | [Next: _Exit()](#)
* * *](#)
Β© 2012-2024 .com | (#) | (#) | (#) | (#)
YouTip