Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Lập Trình C

Chương trình C kiểm tra hàm atexit()


Hàm atexit() cho phép đăng ký hàm sẽ được gọi tự động khi chương trình kết thúc (thoát bình thường).

Là hàm định nghĩa sẵn trong header stdlib.h.

Ví dụ 1

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

void welcome(void) {
    printf("Welcome to New, ");
}

void world(void) {
    printf("World\n");
}

int main() {
    atexit(world);   // Đăng ký gọi sau
    atexit(welcome); // Đăng ký gọi trước (LIFO)
    return 0;
}

Kết quả ví dụ 1

Welcome to New,World

Lưu ý: Các hàm đăng ký sau được gọi trước (LIFO - Last In First Out).

Ví dụ 2

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

void first(void) {
    printf("This is a beautiful, ");
}

void second(void) {
    printf("Wonderful life\n");
}

int main() {
    atexit(second);
    atexit(first);
    return 0;
}

Kết quả ví dụ 2

This is a beautiful,Wonderful life