1 / 6

Passing Functions as Parameters

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.

camdyn
Download Presentation

Passing Functions as Parameters

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Passing Functions as Parameters

  2. 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).

  3. 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); }

  4. 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.

  5. 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); …

  6. 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;

More Related