In this guide, you will learn what is exit() function is in C++ programming and how to use it with an example.
1. exit() Function Overview
The exit() function is used to terminate the program execution and return control to the operating system. Upon calling exit(), all the registered functions with atexit() are executed, and all files opened by the program are closed. It is a part of the C standard library <cstdlib> in C++.
Signature:
void exit(int status);
Parameters:
- status: An integer value that is returned to the operating system as the program's exit status.
2. Source Code Example
#include <iostream>
#include <cstdlib>
void cleanup() {
std::cout << "Performing cleanup tasks!" << std::endl;
}
int main() {
atexit(cleanup); // Register cleanup function to be called on exit
std::cout << "Program execution." << std::endl;
exit(0); // Exit the program
std::cout << "This won't be printed." << std::endl;
return 0;
}
Output:
Program execution. Performing cleanup tasks!
3. Explanation
1. The program starts by registering the cleanup() function using atexit(). This function will be executed when the program is exiting.
2. "Program execution." is printed to the console.
3. The exit(0) function is then called, terminating the program and returning an exit status of 0 to the operating system.
4. Before the program fully terminates, the cleanup() function is called, and "Performing cleanup tasks!" is printed.
5. As the program has already terminated using exit(), the line "This won't be printed." is never executed.
Comments
Post a Comment