49_pdfsam_cs2022

49_pdfsam_cs2022 - Uses of function pointers Writing...

Info iconThis preview shows pages 1–4. Sign up to view the full content.

View Full Document Right Arrow Icon
Uses of function pointers Writing generic code A function can take a function as a parameter Example: a generic function to compute integrals double compute_integral(double a, double b, double (*f)(double)) { /* lots of code */ } double x_squared(double x) { return x * x; } double x_cubed(double x) { return x * x * x; } int main() { compute_integral(0, 1, x_squared); compute_integral(5, 9, x_cubed); }
Background image of page 1

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
Function pointer example #include <stdio.h> void change_array( int *a, int size, int (*f)(int)) { int j; for( j=0; j < size; j++) a[j] = f(a[j]); } int add_one(int x) { return x + 1; } int square(int x) { return x * x; } int main() { int a[5] = { 0, 1, 2, 3, 4 }; change_array(a, 5, add_one); // increment every element change_array(a, 5, square); // square every element return 0; }
Background image of page 2
Other examples qsort(), heapsort(), mergesort() are standard library functions for generic sorting defined in stdlib.h They take a comparison function as a parameter They can sort any type of array, as long as an
Background image of page 3

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
Image of page 4
This is the end of the preview. Sign up to access the rest of the document.

This note was uploaded on 01/10/2010 for the course CS 2022 at Cornell.

Page1 / 6

49_pdfsam_cs2022 - Uses of function pointers Writing...

This preview shows document pages 1 - 4. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online