Hello, I’m Liang Tang.

This is part 29 of the EasyC++ series on function Pointers.

For those who want a better reading experience, visit github repository: EasyLeetCode.

A function pointer

A function pointer is, as its name implies, a pointer to a function.

Similar to data, functions in C++ have addresses. The addresses of functions are the memory addresses that store the code in the function’s machine language. We can pass the address of another function as an argument to the function, so that the function can be flexibly called.

Get function address

Getting the address of a function is as simple as using the function name (no arguments or parentheses). For example, if we have a function called think, think() is to call the function to get the result, and think is to get the address of the function.

If we wanted to pass the think function as an argument to another function, we could write:

func(think);
Copy the code

Declaring function Pointers

Declaring a function pointer is similar to declaring a function. We can declare a function as follows:

double process(int);
Copy the code

We declare a pointer to a function as follows:

double (*pt)(int);
Copy the code

If we replace PI pt with a function name, this is essentially a function declaration. If (*pt) is a function, then pt is a pointer to the function.

Function Pointers pass parameters

If we were to implement a function and one of its arguments was a function pointer, it would be written the same way as before:

double func(double x, double (*pt)(int));
Copy the code

In this declaration, its second argument is a function pointer. The function referred to takes an int and returns a double.

Call a function

Finally, let’s look at calling functions through Pointers.

In fact, it is very simple, because we said that (*pt) has the same effect as a function. We used to call the function by its name, so we just need to call it by (*pt).

Such as:

double process(int);
double (*pt)(int);

pt = process;
cout << (*pt)(5) << endl;
Copy the code