Pointer to a function

Learn how a pointer can point to a function and its use cases.

Introduction

As discussed before, a pointer contains a reference, i.e., it stores the address. This address can be a variable, an array, etc. Simultaneously, the pointer may also point to a function, which means that it can store the address of a function.

We've looked at what a pointer to a function is. But what are its benefits?

A pointer to a function is beneficial in cases where we want to select operations on runtime. For example, we have a function where an if-else the statement is present. Depending on the condition, we want to select the function that is to be called at runtime. Yes, we can do this runtime, but let's suppose this function will later on be passed onto another function. As we don't know what function is going to be passed as a parameter, we create the argument as a pointer to the function instead of specifying it as a function.

They're also very helpful in testing, as they allow us to link the demo/ testing function instead of an actual function.

Declaration

To declare a pointer to a function, we need to specify the function’s return type and parameter types, just like when declaring a function itself.

Create a free account to access the full course.

Continue your learning journey with a 14-day free trial.

By signing up, you agree to Educative's Terms of Service and Privacy Policy