////main.m//Lessonreturnfunpointer////Created by Laouhn on 15/7/29.//Copyright (c) 2015 Chi Hai Tao. All rights reserved.//#import<Foundation/Foundation.h>#import"Function.h"intMainintargcConst Char*argv[]) { //define two functions, Max, Min, sum//int value = MAX (3, 5);//printf ("value =%d \ n", value);// //char s[20] = "D"; //scanf ("%s", &s[20]); //Shuruzhilin (3,5, (p) s); while(1) {printf ("Enter the action you want to perform: Max asks Max, Min min, sum max"); Charstr[ -] = {0}; scanf ("%s", str); intValue = getvalueforstring (3,5, str); printf ("value =%d\n", value); } return 0;}
Function.h
////Function.h//Lessonreturnfunpointer////Created by Laouhn on 15/7/29.//Copyright (c) 2015 Chi Hai Tao. All rights reserved.//#import<Foundation/Foundation.h>//Maximum Valuetypedefint(*func) (int,int);intMaxintAintb);intMinintAintb);intSumintAintb);voidShuruzhilin (int,int, FUNC p); typedefint(*pfun) (int,int);structNamefunctionpair {Charname[ -]; Pfun function; };typedefstructNamefunctionpair Namefunctionpair;//Analysis: Based on the requirements, first used to match the table (print table)---structure array, then the table should be created in which?---funtion.m fileintGetvalueforstring (intAintBCharstr[]); Pfun Getfunctionbyname (Char*string);
Function.m
////function.m//Lessonreturnfunpointer////Created by Laouhn on 15/7/29.//Copyright (c) 2015 Chi Hai Tao. All rights reserved.//#import"Function.h"intMaxintAintb) { returna > B?a:b;}intMinintAintb) { returna > B?b:a;}intSumintAintb) { returnA +b;}voidShuruzhilin (intAintB,func P) { intc =P (A, b); printf ("%d", c);} Namefunctionpair funpair[]= { {"Max", Max}, {"min", Min}, {"sum", Sum}};//the function can help us achieve the goal: more according to the string str matched to the corresponding function, and then, to calculate the two parameters a, b corresponding values, to returnintGetvalueforstring (intAintBCharstr[]) {pfun func= Getfunctionbyname (str);//The function pointer is saved at this time returnfunc (A, b);} Pfun Getfunctionbyname (Char*string){ for(inti =0; I <sizeof(Funpair)/sizeof(funpair[0]); i++) { if(strcmp (string, funpair[i].name) = =0) { returnfunpair[i].function; } } returnMax//returns the Max function when the shot has no return value }
iOS pointer callback function