//  File: fptr1.C
//
//  Exploring function pointers.

#include <iostream.h>
#include <iomanip.h>

// some simple functions

int add3(int n) {
   return n + 3 ;
}

int add5(int n) {
   return n + 5 ;
}


// Takes a function parameter

int apply (int addx(int), int m) {
   return addx(m) ;
}

main() {
   int m = 2, result ; 

   // fptr is a variable that holds the address of a function
   // which takes an int parameter and returns an int.
   //
   int (*fptr)(int) ;

   cout << "m + 3 = " << add3(m) << endl ;
   cout << "m + 5 = " << add5(m) << endl ;
   cout << endl ;

   result = apply(&add3, m) ;
   cout << "Applying add3 to m, result = " << result << endl ; 
   result = apply(&add5, m) ;
   cout << "Applying add5 to m, result = " << result << endl ; 
   cout << endl ;

   fptr = &add3 ;
   result = apply(fptr, m) ;
   cout << "Applying fptr to m, result = " << result << endl ;

   fptr = &add5 ;
   result = apply(fptr, m) ;
   cout << "Applying fptr to m, result = " << result << endl ;

   result = (*fptr) (10) ; // function application has higher precedence
   cout << "Applying fptr to 10, result = " << result << endl ;
}
