Function pointer

A function pointer is a pointer to which the address of the function is assigned. Function pointers allow you to specify a return value and arguments.

// Function pointer
Return type (* variable name) (type name 1, type name 2, ...);

Get the address of the function

You can get the address of a function by omitting the parentheses from the function.

// Get the address of the function
Function name

Call a function from a function pointer

You can call a function from a function pointer. The calling method is the same as a normal function.

Function pointer (argument 1, argument 2, ...);

You can call a function from a function pointer.

Sample using function pointer

This is a sample using a function pointer. I am calling a function using a function pointer.

#include <stdint.h>
#include <stdio.h>

int32_t sum (int32_t num1, int32_t num2);

int main (void) {
  
  // Function pointer
  int32_t (* sum_ptr) (int32_t, int32_t) = sum;
  
  int32_t total = sum_ptr (2, 3);
  
  printf("%d\n", total);
}

int32_t sum (int32_t num1, int32_t num2) {
  int32_t total = num1 + num2;
  
  return total;
}

This is the output result.

Five

What is the address of a function?

It's not just the data that has the address. Functions also have expanded addresses in memory. The address of a function is the first address that indicates the location of the function that exists in memory.

What are function pointers useful for?

Since the address of the function is assigned to the function pointer, the value of the address can be passed to the argument of another function.

When reading a function from a shared library file at run time, you get the address of the function, so you need to assign it to a function pointer.

Function pointers are essential knowledge when retrieving and executing a function from a shared library.

Associated Information