In this guide, you will learn what isexit() function is in C++ programming and how to use it with an example.
1.exit() Function Overview
Theexit() function is used to terminate the program execution and return control to the operating system. Upon callingexit(), all the registered functions withatexit() 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 thecleanup() function usingatexit(). This function will be executed when the program is exiting.
2. "Program execution." is printed to the console.
3. Theexit(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, thecleanup() function is called, and "Performing cleanup tasks!" is printed.
5. As the program has already terminated usingexit(), the line "This won't be printed." is never executed.
Comments
Post a Comment