CS/CE 218 Lecture -*- Outline -*- * pointers to functions (section 5.11) a function is not a variable, but it is an object, so can point to it pointers to functions are first-class citizens, can be stored in arrays, passed to functions, etc. Q: What are some uses for pointers to functions? Important uses for pointers to functions: abstracting algorithms e.g., example in book, use different comparisions for differnent kinds of sorting (page 119...) table-driven designs at run-time, decide what to do, fetch function from table very important in window systems (select from menu) also a key idea in object-oriented programming ------------------ int iterate(int (*f)(int), int num, int x) /* effect: returns f(...(f(x))...) where f is applied num times */ { (num == 0) ? x ? f(iterate(f, num, x)); } /* example call: */ res = iterate(T, 3, 4); ------------------ f is the address of a function, saying f(iterate(&f, num, x)) would be an error, as would be passing a pointer to the variable f not it's value it's better in general not to put & in front of function names they are automatically coerced to their addresses Q: What's the difference between int (*f)(int) and int *f(int) ? the first declares f to be a pointer to a function ... the second declares f as a function that returns an int*