Lab 10 Function Pointer Allows your program to determine which - - PowerPoint PPT Presentation

lab 10 function pointer
SMART_READER_LITE
LIVE PREVIEW

Lab 10 Function Pointer Allows your program to determine which - - PowerPoint PPT Presentation

Lab 10 Function Pointer Allows your program to determine which function to call dynamically. - Example: double (*func) (double x); This function pointer signature is to take a double as parameter, and returns a double. typedef Allow you to


slide-1
SLIDE 1

Lab 10

slide-2
SLIDE 2

Allows your program to determine which function to call dynamically.

  • Example:

double (*func) (double x); This function pointer signature is to take a double as parameter, and returns a double.

Function Pointer

slide-3
SLIDE 3

typedef

Allow you to create alias for a data type, or a function. Example:

  • typedef double Currency;
  • typedef string FiveString[5];
  • typedef double Func(double);
slide-4
SLIDE 4

Function Pointer Example

slide-5
SLIDE 5

Function Pointer Example

slide-6
SLIDE 6

Function Pointer Example

slide-7
SLIDE 7

Function Pointer Example

slide-8
SLIDE 8

Function Pointer

//existing functions: int function1(){ ... } int function2(int x){ ... } int function3(int x,int y){ ... } int function4(int *x){ ... } //declaring a pointer to function: int (*f1)(); int (*f2)(int); Int (*f3)(int, int); int (*f4)(int *);

slide-9
SLIDE 9

#include <iostream> using namespace std; typedef double (*FUNC)(double); double integrate(FUNC f, double a, double b) { // what goes here? } double line(double x){ return x; } double square(double x){ return x*x; } double cube(double x){ return x*x*x; } int main() { cout << "The integral of f(x)=x between 1 and 5 is: " << integrate(line, 1, 5) << endl; // 12 cout << "The integral of f(x)=x^2 between 1 and 5 is: " << integrate(square, 1, 5) << endl; // 41.3333 cout << "The integral of f(x)=x^3 between 1 and 5 is: " << integrate(cube, 1, 5) << endl; // 156 return 0; }

Code outline

slide-10
SLIDE 10

In Integration wit ith fu function pointers

f(x) a b

  • ffset = 0.001

double integrate(FUNC f, double a, double b){ //f is a pointer to the function of type //double function(double x) //use f(x)*offset to compute the area //of one slice; then sum up all slices. //x is the horizontal position of the //rectangle, and f(x) is the height. return area; }