函数指针的定义
typedef int (*compare_ptr)(int,int);// so there is a Type named compare_ptr int max(int x,int y) { return x>y ? x:y; } //!函数指针的定义 //? return-type (* func_ptr) (type1,type2...) printf("max of 1,2,3=%d\n",max(max(1,3),3)); int (*max_ptr)(int,int)=&max; printf("max of 1,2,3=%d\n",max_ptr(max_ptr(1,3),3)); compare_ptr p=&max; printf("max of 1,2,3=%d\n",p(p(1,3),3));
max of 1,2,3=3 max of 1,2,3=3 max of 1,2,3=3
函数指针的 定义有两种: typedef 和Return_type (* func_ptr) (type1,type2...)=&func_name;
typedef 后的类型名字为 func_ptr;
函数指针作参数
typedef int (*compare_ptr)(int,int);// so there is a Type named compare_ptr int max(int x,int y) { return x>y ? x:y; } int min(int x,int y) { return x<y ? x:y; } int find(int array[],int num,int (*func_ptr)(int,int)) { int i,ret=0; for(i=0;i<num-1;i++) { ret=func_ptr(ret,func_ptr(array[i],array[i+1])); // printf("ret=%d\n",ret); } return ret; } //!函数指针作参数 int a[5]={1,45,73,0,8}; printf("max of {1,45,73,0,8}=%d\n",find(a,5,&max)); printf("min of {1,45,73,0,8}=%d\n",find(a,5,&min));
max of {1,45,73,0,8}=73 min of {1,45,73,0,8}=0
max ,min函数在这里称为回调函数;
回调函数在运行时确定 运行代码,可以以此实现c的多态;