Updated December 8, 2023
What is the exit() Function in C language?
The exit() function is the standard library function defined in stdlib.h in C language. You use the exit() function to terminate a function and process in the C programming language. Any open file and function from a process will be closed whenever you call the exit() function. Therefore, you can terminate the current program forcefully and then provide control to the operating system. There are two categories of exit() function: exit(1) and exit(0). The exit(1) terminates the program with the execution process. The exit(0) terminates the function without any error message.
Since exit() is part of stdlib.h you need to include it in your C program. You can clean and flush all open stream data (read and write) with rewritten buffered data. Hence, exit() is used to close all these opened files and functions. It also closes all files created by the tmpfile function.
Table of Content
- What is the exit() Function in C language?
- Syntax
- How does the exit() function work in C?
- Types of exit status
- Using exit() for Error Handling
- Alternatives to exit()
- Best Practices and Consideration
- Pitfalls and Common Mistakes
Syntax
void exit (int status);
Since exit() has no return type, use void here as the return type in C programming language. The variable status represents its status value, which is returned to the parent process.
Consider this example: we used the exit() function in the for loop. We have used exit(0) to terminate the function normally.
Code:
#include <stdio.h>
#include <stdlib.h>
int main() {
// Declaration of variables
int counter, limit;
// User input for the limit
printf("Enter the limit: ");
scanf("%d", &limit);
// Loop to iterate through numbers
for (counter = 1; counter < limit; counter++) {
// Check if the counter is 8
if (counter == 8)
// Terminate the program if the counter is 8
exit(0);
else
// Print the current number
printf("\nNumber is %d", counter);
}
return 0;
}
It will give the output after taking user input:
How does the exit() function work in C?
Upon invocation, the exit() function in C carries out the following operations:
- Flushes unwritten buffered data.
- Closes all open files.
- Removes temporary files.
- Returns an integer exit status to the operating system.
Types of exit status
There are two types of exit status in C language. These are EXIT_SUCCESS and EXIT_FAILURE. We will discuss these in brief.
1. EXIT_SUCCESS
This is the exit type of the code. You can use exit(0) to represent this type of status code. It says the program has been terminated without any error or failure.
Syntax:
exit (EXIT_SUCCESS);
Consider the following program for exit(0) status code.
Code:
#include <stdio.h>
#include <stdlib.h>
int main() {
printf("Encountered a critical point; exiting the program.\n");
exit(0); // to terminate program successfully
printf("This code will not be reached.\n");
return 0;
}
The output will be,
Consider another example for exit(EXIT_SUCCESS);
Code:
#include <stdio.h>
#include <stdlib.h>
int main() {
int userNumber;
printf("Please enter an integer: ");
scanf("%d", &userNumber);
if (userNumber == 42) {
printf("Congratulations, you chose the magic number 42.");
exit(EXIT_SUCCESS);
} else {
printf("You did not enter the magic number 42.");
}
return 0;
}
If you will provide input 42, then it will print this:
If the user enters any other integer, the program will output:
2. EXIT_FAILURE
It is a type of exit() status code. This is used to terminate programs abnormally, which means there could be errors. It terminates the process and gives back control to the operating system. It can be represented by exit(1). 1 indicates abnormal termination. Note that you can return any non-zero value in case of failure.
Syntax:
exit (EXIT_FAILURE);
Consider the following C example for exit(1):
Code:
#include <stdio.h>
#include <stdlib.h>
int main() {
int input1, input2;
printf("Enter the first integer: ");
scanf("%d", &input1);
printf("\nEnter the second integer: ");
scanf("%d", &input2);
if (input2 == 0) {
printf("\nDivisor cannot be zero.");
exit(1); // Use EXIT_FAILURE
}
float result = (float)input1 / (float)input2;
printf("%d / %d : %f", input1, input2, result);
exit(0); // Use EXIT_SUCCESS
}
The output depends on user input. Giving the second input non-zero will print the division of these numbers; otherwise, it will be an error message. For example, if you give 10 and 2 as input, respectively, then the output will be:
If you give the second number as 0, then it will print, irrespective of the first input:
Therefore, the program will be terminated abnormally with an error message. Consider another example of EXIT_FAILURE:
Code:
#include <stdio.h>
#include <stdlib.h>
int main() {
// Declare a file pointer and open a file in read mode
FILE *filePointer = fopen("data.txt", "r");
// Check if the file pointer is null
if (filePointer == NULL) {
// Print an error message and exit the program with failure status
fprintf(stderr, "Error: Unable to open the specified file 'data.txt'\n");
exit(EXIT_FAILURE);
}
// Close the file
fclose(filePointer);
printf("File 'data.txt' opened successfully for reading.\n");
printf("Program execution completed.");
return 0;
}
The output depends on the location of the data.txt file. If the data.txt file exits, then it will print the following:
Otherwise, if the file does not exist or there is any error while opening it, Then the program terminates abnormally with an error message:
Therefore, this is a summary:
Parameter Value | Description |
EXIT_FAILURE | Program terminated unsuccessfully (corresponding numeric value: 1) |
1 | Program terminated unsuccessfully (equivalent to EXIT_FAILURE) |
EXIT_SUCCESS | Program terminated successfully (corresponding numeric value: 0) |
0 | Program terminated successfully (equivalent to EXIT_SUCCESS) |
Using exit() for Error Handling
Since the exit() function in C is used for terminating programs abnormally. It is used when an error condition occurs. It performs cleanup operations like closing files and freeing resources. The exit() function is useful when further execution is not feasible because of unrecoverable errors.
For example,
#include <stdio.h>
#include <stdlib.h>
int main() {
FILE *file = fopen("example.txt", "r");
// Check if file opening was successful
if (file == NULL) {
fprintf(stderr, "Error: Unable to open the file.\n");
exit(EXIT_FAILURE);
}
// File processing code goes here
fclose(file);
return 0;
}
The program tries to open a given file for reading in the above example. If the opening file fails, then it prints the error to the standard error stream and exits the program.
Alternatives to exit()
Since the exit() function deals with errors and cleanup, you can use an alternative for error handling and cleanup operation. We have discussed these alternatives below.
Return Statement
You can also use return statements instead of the exit() function to stop the program abnormally. The return statement returns specific values to indicate success and failure. This method is more flexible than exist() method.
Code:
#include<stdio.h>
int divide(int dividend, int divisor) {
if (divisor == 0) {
fprintf(stderr, "Error: Division by zero is not allowed.\n");
return -1; // Return an error code
}
float result = (float)dividend / (float)divisor;
printf("%d / %d : %f\n", dividend, divisor, result);
return 0; // Return success
}
int main() {
int dividend, divisor;
// User input for dividend and divisor
printf("Enter the dividend: ");
scanf("%d", ÷nd);
printf("Enter the divisor: ");
scanf("%d", &divisor);
// Call the divide function
int result = divide(dividend, divisor);
// Check the result of the divide function
if (result == -1) {
// Handle error condition
printf("Division failed. Please check your input.\n");
}
return 0;
}
Output:
The divide function returns -1 when an error occurs, i.e., in the case of divide by zero. Then, the main function tells the user accordingly.
Cleanup Functions
Cleanup functions are used to clean up operations before exiting the program.
Code:
#include <stdio.h>
#include <stdlib.h>
void cleanup() {
printf("Cleaning up resources...\n");
// Additional cleanup code can be added here
}
int main() {
// Program logic goes here
// Cleanup resources
cleanup();
return 0;
}
This code calls the cleanup function just before exiting the program.
Best Practices and Consideration
Note that the priorities are contradictory in the exist() function. These are not just thoughts. You should avoid exit() for reusable libraries. In a multithreaded program, exit() ensures immediate termination. Note that exit is not recoverable, so use it with caution. The best approach prefers returning an error indicator over exit() for flexibility.
Pitfalls and Common Mistakes
These are common things that could be improved while using the exit() function in the C programming language. You should be careful while using it.
- Avoid the use of exit() too soon in your program. It would be best if you considered the consequences.
- Since exit() may not handle all resources correctly. So, you need to release memory before calling it.
- You should use EXIT_SUCCESS and EXIT_FAILURE instead of exit(0) and exit(1) for clarity purposes.
- To avoid unexpected terminations, you should be careful while using exit() in reusable libraries.
- You should be careful while using exit() in multithreaded programs. It may abruptly terminate all threads.
- Since there is no chance of recovery, consider alternatives for controlled shutdown.
- Global variables affected by exit() may lead to unexpected behavior.
- The exit() does not handle signals. So you need to register handlers for graceful program termination.
Conclusion
The exit() is a standard library function under stdlib.h header file C programming language. The exit() function is used to terminate a running process. Two types of exit() function status codes exist: EXIT_SUCCESS and EXIT_FAILURE. We can also represent these by exit(0) and exit(1). Exit (0) is used to terminate a process without error, and exit(1) is used to terminate a process with an error. No return type of exit() function exists, so we can use void as a return in C programming language. It can take an integer value as argument.
Recommended Articles
We hope this EDUCBA information on “Exit Function in C” benefited you. You can view EDUCBA’s recommended articles for more information,