I thought the main function was the first called function. Later I found that the operating system would call a startup function to initialize the C ++ Runtime Library.
After the main function is returned, the operating system recycles resources, but you do not know an important function-atexit ().
Some operations such as releasing resources are required when the program exits, but there are many exit operations. It may be that a value in the end range of the main function is passed to exit (), there may also be some other reasons, so a method unrelated to the program termination method is required to handle the exit of the program.
Function prototype: int atexit (void (*) (void ));
Function: registers a function, which is called at the end of the program.
# Include <cstdlib>
# Include <iostream>
Using namespace std;
Void fun1 ()
{
Cout <"fun1" <endl;
}
Void fun2 ()
{
Cout <"fun2" <endl;
}
Int main ()
{
Atexit (fun1); // register fun1, called when the main function is terminated
Atexit (fun2); // register fun2, called when the main function is terminated
Cout <"mian exit" <endl;
Return 0;
}
// Running result:
Main exit
Fun2
Fun1
The results show that the functions fun1 and fun2 are called after the main function is completed, and the call order is the opposite to the registration order.
From C Xiaojia