1. 程式人生 > >C++中_onexit()用法簡述

C++中_onexit()用法簡述

引問:main 主函式執行完畢後,是否可能會再執行一段程式碼?

答案:可以,可以用_onexit 註冊一個函式,它會在main 之後執行。

知識瞭解:

(1)使用格式:_onexit(int fun()) ,其中函式fun()必須是帶有int型別返回值的無引數函式;

(2)_onexit() 包含在標頭檔案cstdlib中,cstdlib為c語言中的庫函式;

(3)無論函式_onexit() 放到main中任意位置,它都是最後執行。

程式舉例分析:

#include
#include
using namespace std;


int func1(),func2(),func3();

int main(int argc,char * argv[]){

_onexit(func2);
_onexit(func1); //在此處不斷排列組合三條語句的執行順序
_onexit(func3);
cout<<"First Line"< cout<<"Second Line"<}

int func1()
{
cout<<"fun1() executed!"< return 0;
}

int func2()
{
cout<<"fun2() executed!"< return 0;
}
int func3()
{
cout<<"fun3() executed!"< return 0;
}

根據多次重新排列組合 _onexit(func2); _onexit(func1); _onexit(func3);的執行順序可知:_onexit()在main()中越靠後,則其執行順序越靠前;即越在前面的就越延後執行,有點類似‘棧’(先進後出)的特點。