---
title: "main函数结束后怎么继续执行一段代码？"
author: "runfeel"
date: "2013-07-10T15:39:00Z"
tags: []
slug: "main"
draft: false
lastmod: "2013-07-12T13:54:44Z"
id: 1904475
url: "https://runfeel.iteye.com/blog/1904475"
---

在main函数执行结束后，还想继续执行一段甚至多段代码，这就需要用\_onexit注册一个函数，使该函数在main结束后执行。\_onexit(funname);其中参数是一个函数名，且该函数无参数，返回值为int。看代码：

```
#include <iostream>
using namespace std;
int fun1()
{
	cout<<"this is in func1 \n";
	return 1;
}
int fun2()
{
	cout<<"this is in func2 \n";
	return 1;
}
void main()
{
  _onexit(fun1);
  _onexit(fun2);

  cout<<"this is in main\n";
}
```

运行结果如下：

![](http://img.blog.csdn.net/20130710153331296)

先执行main中的输出，跳过了注册的函数，main结束后逆序执行注册的main外执行的函数体