atexit() ใช้ลงทะเบียนฟังก์ชันให้ทำงานอัตโนมัติเมื่อโปรแกรมจบ (normal termination) อยู่ใน
ตัวอย่างที่ 1: เรียก 2 ฟังก์ชันตอนจบโปรแกรม (LIFO - เรียกย้อนกลับ)
#include <stdio.h>
#include <stdlib.h>
void welcome() { printf("Welcome to New, "); }
void world() { printf("World\n"); }
int main() {
atexit(world); // ลงทะเบียนก่อน -> รันทีหลัง
atexit(welcome); // ลงทะเบียนทีหลัง -> รันก่อน
return 0;
}
ผลลัพธ์
Welcome to New, World
ตัวอย่างที่ 2
#include <stdio.h>
#include <stdlib.h>
void first() { printf("This is a beautiful, "); }
void second() { printf("Wonderful life\n"); }
int main() {
atexit(second);
atexit(first);
return 0;
}
ผลลัพธ์
This is a beautiful, Wonderful life
หมายเหตุ: ฟังก์ชันที่ลงทะเบียนทีหลังจะถูกเรียกก่อน (Stack/LIFO order) สามารถลงทะเบียนได้สูงสุด 32 ฟังก์ชัน