60 likes | 151 Views
Passing Functions as Parameters. Functions as entities. Third class entities: The only thing you can do with a function is call it. Early Fortran, Ada-83. Second class entities: You can also pass it as an argument to another function. Pascal.
E N D
Functions as entities • Third class entities: The only thing you can do with a function is call it. Early Fortran, Ada-83. • Second class entities: You can also pass it as an argument to another function. Pascal. • First class entities (defn 1): You can also return it as the value of a function call or assign it as a value of a variable. • First class entities (defn 2): You can also generate new functions at run time. Functional languages (Lisp, ML), many scripting language (C#, Perl, Python).
In C void applyToArray(fp,a,b,n) int (*fp)(), a[], b[],n) { for (int i=0; i<n; i++) b[i] = (*fp)(a[i]); } int square(int N) { return(N*N); } void main() { int a[3] = {1,2,3}, b[3]; applyToArray(square,a,b,3); for(int i=0; i<3; i++) printf(“%i “, i); }
Implementation main passes starting address of “square” as argument to applyToArray. applyToArray finds value of fp to be address of “square”, jumps there. Otherwise, same as any other calling sequence. Note: The type returned by fp is declared, but neither the type nor number of its arguments are declared.
Other operations on function pointers in C You can assign to a function pointer variable, but that’s pretty much all. int (*powerFunction)() (int n) { int (*fp)(), i; fp = square; i = (*fp)(3); …
C++ C++ is similar, except that • Declare types of arguments • Can return function as value of function. typedef int (*MapsIntToInt) (int); MapsIntToInt fp; fp = square;