回调函数例子

在网上找的,引于一个台湾同胞的
//---------------------------------------------------
//說明:                                                 
//        這個是一個callback function...                 
//        由Google上找到的例子加以修改而成的...         
//---------------------------------------------------
//若要測試,記得只能存成.c檔...
//(有warning,可以不用理)
//不可以存成.cpp檔...因為complier不會過...             
//---------------------------------------------------
#include <stdio.h>
//就是structure
struct table
{
    char id;
    void *func;
};

void *funcA() { printf("This is funcA()\n"); }
void *funcB() { printf("This is funcB()\n"); }
void *funcC() { printf("This is funcC()\n"); }
void *funcD() { printf("This is funcD()\n"); }

const struct table tb[] = { {1, funcA},
                            {2, funcB},
                            {3, funcC},
                            {4, funcD} };
//宣告callback function的prototype(原型)
void (*func)(void);        
int main(int argc,char *argv[])
{
    int index, i;
    index = 1;
    for (i = 0; i < 4; i++)
    {
        if (index == tb[i].id)
        {
            func = tb[i].func;
            func();//呼叫callback function
        }
        index++;
    }
    printf("如果在這裡呼叫callback function呢?\n");
    func();
return 0;
}

輸出的結果:
This is funcA()
This is funcB()
This is funcC()
This is funcD()
如果在這裡呼叫callback function呢?
This is funcD()
Press any key to continue

你可能感兴趣的:(回调函数例子)