![]() |
VOOZH | about |
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++.
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++:
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++
The following program illustrates the use of exit(1) to terminate a program in C++:
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.