淡水求咸

博客园已经停止更新,请移步 http://lovecjh.com/

导航

C++一道面试题(atexit)

题:main主函数执行完毕后,是是否可能会再执行一段代码?给出说明。

答:如果需要加入一段在main退出后执行的代码,可以使用atexit()函数注册一个函数,代码如下:

#include <stdio.h>
#include <stdlib.h>

int atexit(void(*function)(void));
void fn1(void),fn2(void),fn3(void),fn4(void);

int main()
{
atexit(fn1);
atexit(fn2);
atexit(fn3);
atexit(fn4);
printf("This is executed first.\n");

return 0;
}

void fn1()
{
printf(" next.\n");
}

void fn2()
{
printf(" executed ");
}

void fn3()
{
printf(" is");
}

void fn4()
{
printf("This");
}

执行结果:

This is executed first.
This is executed next.

说明:

(1)函数原型:int atexit( void ( __cdecl *func )( void ) );

(2)The atexit function is passed the address of a function (func) to be called when the program   terminates normally. Successive calls to atexit create a register of functions that are executed in LIFO (last-in-first-out) order. The functions passed to atexit cannot take parameters. atexit and _onexit use the heap to hold the register of functions. Thus, the number of functions that can be registered is limited only by heap memory.



posted on 2012-03-12 09:41  深圳彦祖  阅读(398)  评论(0编辑  收藏  举报