Home>

Calling functions with function pointer variables

Pointer variables can also point to a function.A function is assigned an entry address at compile time.This function entry address is called a function pointer.You can use a pointer variable to point to a function,This function is then called from that pointer variable.

For example, find the greater of a or b.

First write the program as usual:

#include<iostream>
using namespace std;
int main ()
{
  int max (int x, int y);//function declaration
  int a, b, m;
  cin>>a>>b;
  m=max (a, b);//Call the function max to find the maximum value,Assigned to m
  cout<"max<<m<endl;
  return 0;
}
int max (int x, int y)
{
  int z;
  if (x>y) z=x;
  else z=y;
  return (z);
}

You can use a pointer variable to point to the max function, and then call this function through the pointer variable.To define a pointer variable to the max function:

Compare this to the prototype of the function max:

 int max (int, int);//max function prototype

As you can see:Just replace (* p) max, everything else is the same.Now modify the main function of the above program as follows:

#include<iostream>
using namespace std;
int main ()
{
  int max (int x, int y);//function declaration
  int (* p) (int, int);//Define a pointer variable p to a function p
  int a, b, m;
  p=max;//make p point to function max
  cin>>a>>b;
  m=p (a, b);
  cout<"max ="<m<endl;
  return 0;
}

Notice the assignment "p=max;" on line 7. Do not miss this sentence,Its role is to assign the entry address of the function max to the pointer variable p. At this point, p points to the function max.

The general definition of a pointer variable to a function is:

Function type (* pointer variable name) (function parameter list);

C++ function that returns a pointer value

A function can bring back an integer value, a character value, a real value, etc.You can also bring back pointer data,That is the address. The concept is similar to before,It's just that the type of the value returned is a pointer type.A function that returns a pointer value is simply called a pointer function.

The general form of defining a pointer function is:

Type name * function name (parameter list);

E.g:

 int * a (int x, int y);
c
  • Previous Step by step to teach you to create a table partition of the SQL database
  • Next Analysis of CheckBox and RadioButton usage examples for Android controls