Function Pointer

Pointers

Pointers are the data types that can be used to store the address of some data stored in computer's memory. Pointers are mostly used as a data type that would store address of other variables.

Pointers can point to data/functions where data could be stored as a constant or a variable. We can also use pointers to dereference and get the value at whatever address the pointer is pointing at. 

// <varaible_type> *<name>
// example:
int data;
int *pointer_to_integer = &data;

 


Function Pointers

Function pointers are used to store address of functions. We need function pointers to make "callbacks", but let us understand the basic syntax first.

Function Pointer Syntax

1. If function return type is void

void (*func_pointer)(void);

Let us re-read the syntax, *func_pointer is the pointer to a function. void is the return type of that function, and finally void is the argument type of that function. 

2. If function returns an int and has a char* as an input parameter, then code looks like this:

int (*func_pointer)(char *)

In this example:

  1. *func_pointer is the function pointer
  2. int is the return type of that function
  3. char* is the type of the argument.

 


Examples

Code Example 1: Function pointers with an int as an argument

#include <stdio.h>

void function(int arg) {
  printf("Function being called and arg is: %d\n", arg);
}

int main(void) {
  void (*func_pointer)(int);
  
  // assign function to the function pointer
  func_pointer = &function;
  
  // call the function pointer
  (*func_pointer)(6);
  
  // Or call it like this:
  func_pointer(6);
}

Code Example 2: Function pointer returns and taking argument as void data type.

// Let us "typedef" the function pointer: void void_function(void);
typedef void (*void_function_t)(void);

void foo(void) {
  puts("Hello"); 
}

int main(void) {
  // assign function to the function pointer
  void_function_t func_pointer = foo;
  
  // call the function pointer
  func_pointer();
}

Code Example 3: How to use array of functions using function pointers.

void foo(void) { puts("foo"); }
void bar(void) { puts("bar"); }

// Typedef a function with void argument, returning nothing (void)
typedef void (*void_function_t)(void);

int main(void) {
  // assign array of functions to the function pointer
  void_function_t func_pointers[] = {foo, bar};
  
  // call the function pointers
  func_pointers[0]();
  func_pointers[1]();
}

 

Back to top