main主函数执行完毕后,是否可能会再执行一段代码

可以使用atexit()函数注册一个函数

  1. #include <stdlib.h>

  2. //功能:Processes the specified function at exit.
  3. //格式:int atexit( void ( __cdecl *func )( void ) );
  4. //描述:The atexit function is passed the address of a function (func) to be
  5. // called when the program terminates normally. Successive calls to atexit 
  6. //create a register of functions that are executed in LIFO (last-in-first-out) 
  7. //order. The functions passed to atexit cannot take parameters. atexit and 
  8. //_onexit use the heap to hold the register of functions. Thus, the number of
  9. // functions that can be registered is limited only by heap memory.
  10. int atexit (void (*function)(void));


  11. #include <stdio.h>

  12. void fun1(void);

  13. void fun2(void);

  14. void fun3(void);

  15. void fun4(void);

  16. void main()

  17. {
  18.     
  19.     atexit(fun1);
  20.     
  21.     atexit(fun2);
  22.     
  23.     atexit(fun3);
  24.     
  25.     atexit(fun4);
  26.     
  27.     printf("this is executed first.\n");
  28.     
  29. }

  30. void fun1() 
  31. {
  32.     printf("next.\n");
  33. }

  34. void fun2()
  35. {    
  36.     printf("executed ");    
  37. }

  38. void fun3()
  39. {    
  40.     printf("is ");    
  41. }

  42. void fun4()
  43. {    
  44.     printf("this ");    
  45. }

 

 

结果:
This is executed first.
This is executed next.

注意,atexit()以栈的方式注册函数,后注册的函数会先执行

全局类的析构函数好象也在main后执行

non-local static object的构造函数在main之前执行,析构函数在main之后执行。
关于这些函数是如何执行的,以及atexit注册的函数是如何被执行的,可以参见crt的源文件。
在vc.net中,这个文件应该是在...\Microsoft Visual Studio .NET 2003\Vc7\crt\src\crt0.c
通过step into,你也可以跟踪整个程序被crt控制执行的过程。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值