实例一
#include
int add(int a,int b)
{
return a+b;
}
int minus(int a,int b)
{
return a-b;
}
int multipl(int a,int b)
{
return a*b;
}
int divider(int a,int b)
{
return a/b;
}
static int (*calc_callback)(int,int) = NULL;
typedef int (*CALLBACK)(int,int);
CALLBACK callback;
int test_callback(callback)
{
calc_callback = callback;
return 0;
}
void main()
{
int result;
test_callback(add);
result=calc_callback(9,3);
printf("result:%d\n",result);
test_callback(divider);
result=calc_callback(9,3);
printf("result:%d\n",result);
test_callback(multipl);
result=calc_callback(9,3);
printf("result:%d\n",result);
test_callback(minus);
result=calc_callback(9,3);
printf("result:%d\n",result);
}
运行结果:
gcc callbackFun.c -o callback
./callback
result:12
result:3
result:27
result:6
实例二:
#include
typedef int (*P_FUN)(int, int);
int add(int a,int b)
{
printf("add\n");
return a+b;
}
int sub(int a,int b)
{
printf("sub\n");
return a-b;
}
int minus(int a,int b)
{
printf("minus\n");
return a*b;
}
int diver(int a,int b)
{
printf("diver\n");
return a/b;
}
P_FUN p_fun[] = {
add,
sub,
minus,
diver,
};
void main()
{
P_FUN *ptr_f = NULL;
for(ptr_f = &p_fun[0];*ptr_f;ptr_f++){
(*ptr_f)(33, 3);
}
}
阅读(2099) | 评论(0) | 转发(0) |