3月23日 三

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.

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值