In C++, the exit function allows the users to terminate the execution of a program immediately and return the control to the operating system. In this article, we will learn about exit(1) in C++.
What does exit(1) mean in a C++ Program?
The exit() function defined in the <cstdlib> header in C++ terminates the currently executing program and immediately returns the control to the operating system. The function takes an integer argument exit status code to be returned to the operating system. If the value of the exit status code is 0 it denotes that the program was executed successfully however if the value of the status code is 1 it denotes that there is some error in the code and the program was terminated abnormally. Below is the syntax for the exit function in C++:
Syntax
void exit(1)here, exit status code 1 will denote the program's abnormal termination.
To learn more about the different exit status codes you can refer to this article -> Exit Codes in C++
Example of exit(1)
The following program illustrates the use of exit(1) to terminate a program in C++:
// C++ Program to demonstrate how to use exit(1)
#include <cstdlib>
#include <fstream>
#include <iostream>
using namespace std;
// Function to process a text file
void processFile(const string& filename)
{
// Open the file
ifstream file(filename);
// Check if the file opened successfully
if (!file) {
// Print an error message if the file does not exist
// or cannot be opened
cerr << "Error: File " << filename << " not found."
<< endl;
// Exit the program with status 1 indicating an
// error if the file was not found
exit(1);
}
// Variable to store each line of the file
string line;
// Read the file line by line
while (getline(file, line)) {
// Process each line of the file
// In this case, we are simply printing the line to
// the console
cout << line << endl;
}
// Close the file after processing
file.close();
}
int main()
{
// Declare the name of the file to be processed
string filename = "example.txt";
// Call the function to process the file
processFile(filename);
return 0;
}
Output
ERROR!
Error: File example.txt not found.
Time Complexity: O(1)
Auxiliary Space: O(1)
Explanation: In the above program, we have declared a function processFile that takes the name of a text file as an input and process the text file line by line. Inside the processFile function we have used exit(1) for error handling, if the file name passed as an argument is not valid then the exit(1) function is executed immediately indicating that the program was not executed successfully.