读书人

main主函数执行完毕后是否可能再执行

发布时间: 2012-02-27 10:00:22 作者: rapoo

main主函数执行完毕后,是否可能再执行一段代码??请问大家
本人最近在看下笔试题,看到这么一题
main主函数执行完毕后,是否可能再执行一段代码??请问大家
书上说使用atexit函数注册一个函数.有一段代码:
#include <iostream.h>
#include <stdlib.h>
#include <stdio.h>
int atexit(void (*function)(void));
#include <string.h>

#include <stdlib.h>
#include <stdio.h>
void fn1(void),fn2(void),fn3(void),fn4(void);
int main(void)
{
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.

我不大明白为什么输出:This is executed next,而不是next executed is this.

也不大明白注册的函数怎么调用的?
请大家发表下看法呢?能详细点.


[解决办法]
main函数退出后,会在调用exit函数,而exit函数里对依次调用atexit注册的函数,不过调用顺序是和atexit注册顺序相反的。

读书人网 >C语言

热点推荐