C ++ and object-oriented learning notes -- call after the main function is completed

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.