`
zmfbird
  • 浏览: 49253 次
  • 性别: Icon_minigender_2
  • 来自: 西安
最近访客 更多访客>>
社区版块
存档分类
最新评论

3月23日 三

    博客分类:
  • c++
阅读更多

1.main主函数执行完毕后,是否可能会再执行一段代码,给出说明。(朗讯面试题)

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

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

void fn1( void ), fn2( void ), fn3( void ), fn4( void );

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

void main( void )
{
atexit( fn1 );
atexit( fn2 );
atexit( fn3 );
atexit( fn4 );

printf( “This is executed first.\n” );

return;
}

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.

讲解:

atexit
Processes the specified function at exit.

int atexit( void ( __cdecl *func )( void ) );

Routine  Required Header   Compatibility 
atexit < stdlib.h>         ANSI, Win 95, Win NT 


For additional compatibility information, see Compatibility in the Introduction.

Libraries

LIBC.LIB Single thread static library, retail version 
LIBCMT.LIB Multithread static library, retail version 
MSVCRT.LIB Import library for MSVCRT.DLL, retail version 


To generate an ANSI-compliant application, use the ANSI-standard atexit function (rather than the similar _onexit function).

Return Value

atexit returns 0 if successful, or a nonzero value if an error occurs. 

Parameter

func

Function to be called

Remarks

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.

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics