exit()和atexit()函数

作者:追风剑情 发布于:2020-3-20 15:43 分类:C

示例:为退出程序注册回调函数

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h> //C99特性
#include <string.h>
#include <math.h>
#include <ctype.h>
#include <tgmath.h>

//atexit()的注册函数必须返回void,并且参数也为void
void sign_off(void);
void too_bad(void);

int main(int argc, char* argv[])
{
	int n;

	/* 注册 sign_off()函数 */
	atexit(sign_off);
	puts("Enter an integer:");
	if (scanf("%d", &n) != 1)
	{
		puts("That's no integer!");
		atexit(too_bad); /* 注册 too_bad()函数 */
		exit(EXIT_FAILURE); //当调用exit()时,会调用atexit()注册的函数
		//ANSI保证,可以用atexit()注册至少32个函数,调用顺序与注册顺序相反。
	}
	printf("%d is %s.\n", n, (n % 2 == 0) ? "even" : "odd");
	//失败:EXIT_FAILURE
	//成功:EXIT_SUCCESS
	//exit(EXIT_SUCCESS);

	system("pause");
	return 0; //main()函数退出时会自动调用exit()
}

void sign_off(void)
{
	puts("Thus terminates another magnificent program from");
	puts("SeeSaw Software!");
}

void too_bad(void)
{
	puts("SeeSaw Software extends its heartfelt condolences");
	puts("to you upon the failure of your program.");
}

运行测试
111.png

标签: C语言

Powered by emlog  蜀ICP备18021003号-1   sitemap

川公网安备 51019002001593号