/* File: func4.c Returning a function in C */ #include float total (float x, int m) { return x + (float) m ; } float withInterest (float x, int m) { return x * 1.1 + (float) m ; } float apply( float (*f) (float, int), int A[], int n) { float accumulate = 0.0 ; for (int i=0 ; i < n ; i++) { accumulate = f(accumulate, A[i] ) ; } return accumulate ; } float (*select (int pick)) (float, int) { if (pick == 0) return total ; else return withInterest ; } int main () { int B[10] = { 10, 11, 12, 13, 14, 15, 16, 17, 18, 19} ; float result ; float (*func)(float, int) ; printf("Before:\n") ; for (int i=0 ; i < 10 ; i++) { printf(" B[%d] = %d\n", i, B[i]) ; } func = select(0) ; result = apply (func, B, 10) ; printf("\n\nAfter calling apply(total, B, 10):\n") ; printf(" result = %f\n", result) ; func = select(1) ; result = apply (func, B, 10) ; printf("\n\nAfter calling apply(withInterest, B, 10):\n") ; printf(" result = %f\n", result) ; }