设计main函数退出后继续执行一段代码

原理:

  使用 _onexit() 函数注册一个函数,这个函数会在main函数退出后执行

使用原则:

  1、包含在cstdlib中是c语言中的库函数;

  2、需要注册的函数格式为:int类型返回值、无参数,参见_onexit()定义;

  3、无论_onexit函数放到main中哪个位置,相应的已注册函数都是最后执行;

  4、如果用_onexit注册了多个函数, 则已注册函数的执行顺序跟注册顺序相反;

测试代码:

 1 #include "stdafx.h"
 2 #include <iostream>
 3 #include <cstdlib>
 4 
 5 using namespace std;
 6 
 7 
 8 int test1( int nV1, int nV2 )
 9 {
10     cout << "in test1()" << endl;
11     return nV1+nV2;
12 }
13 
14 int fun1()
15 {
16     cout << "excute fun1" << endl;
17     return 0;
18 }
19 
20 int fun2()
21 {
22     cout << "excute fun2" << endl;
23     return 0;
24 }
25 
26 int main(int argc, char* argv[])
27 {
28     //_onexit(test1); //error C2664: '_onexit' : cannot convert parameter 1 from 'int (int,int)' to 'int (__cdecl *)(void)'
29 
30     _onexit(fun1);
31 
32     cout << "exit" << endl;
33 
34     _onexit(fun2);
35 
36     return 0;
37 }

输出结果:

  exit

  excute fun2

  excute fun1

 

转载于:https://www.cnblogs.com/weiquxiong/p/3554223.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值