Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

function
pointer
c

What is a function pointer in C?

Educative Answers Team

Just like an integer pointer or a char pointer, a function pointer is a variable that stores the address of a function.


Syntax

A function pointer is initialized as follows:

void (*funcPtr)(int);

We can breakdown the above syntax into the following components:

  • funcPtr is a pointer to a function.
  • void is the return type of that function.
  • int is the datatype of the argument of that function.

Once initialized, you can make funcPtr point to a function like this:

funcPtr = &foo;

foo is the name of the function which is being pointed to.

Note: The ampersand (&) sign is optional. Writing funcPtr = foo; is a valid syntax as well.

The illustration below shows how funcPtr points to the function foo. The funcPtr variable simply stores the address of the function.

svg viewer
Function pointers 'point' to functions by storing their starting address

Examples

Consider the example below which uses a function pointer to a void function.

In lines 6 and 7 of the code snippet below, the variable funcPtr points to the function showMessage(). The function is then called, using the name of the function pointer variable funcPtr.

void showMessage() {
  printf("Hello from the function.");
}

int main() {
  void (*funcPtr)();
  funcPtr = &showMessage;
  funcPtr();
}

Let’s have a look at another example which utilizes a function pointer that takes several arguments.

In the example below, the multiplier takes three integers as arguments, the function pointer, to the function multiplier, is initialized with the three integers in line 6.

The function is invoked using the name of the function pointer variable funcPtr.

int multiplier(int num1, int num2, int num3) {
  return num1 * num2 * num3;
}

int main() {
  int (*funcPtr)(int, int, int);
  funcPtr = &multiplier;
  int result = funcPtr(5,5,2);
  printf("%d", result);
}

RELATED TAGS

function
pointer
c
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring