首页 > 代码库 > 函数指针
函数指针
/*Author:Choas Lee *Date:2012-02-28 */ #include<stdio.h> #include<stdlib.h> #include<string.h> float add(float a,float b){return a+b;} float minus(float a,float b){return a-b;} float multiply(float a,float b){return a*b;} float divide(float a,float b){return a/b;} //该函数的返回值是一个函数 float(* FunctionMap(char op) )(float,float) { switch(op) { case ‘+‘: return add; break; case ‘-‘: return minus; break; case ‘*‘: return multiply; break; case ‘\\‘: return divide; break; default: exit(1); } } int main() { float a=10,b=5; char ops[]={‘+‘,‘-‘,‘*‘,‘\\‘}; int len=strlen(ops); int i=0; float (*returned_function_pointer)(float,float);//定义了一个函数指针 for(i=0;i<len;i++) { returned_function_pointer=FunctionMap(ops[i]); printf("the result caculated by the operator %c is %f\n",ops[i],returned_function_pointer(a,b)); } return 0; }
输出:
the result caculated by the operator + is 15.000000 the result caculated by the operator - is 5.000000 the result caculated by the operator * is 50.000000 the result caculated by the operator \ is 2.000000
参考:
1.http://hipercomer.blog.51cto.com/4415661/792301
函数指针
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。