The C Programming Language

Introduction

Preface

In this article, I'll explain what function pointers are and how to use them. We'll also learn about function pointer arrays and their syntax.

Prerequisites

In order to follow along, make sure you're familiar with these topics:

Knowledge of structs will be useful, but otherwise, won't hinder your understanding of the idea of functions pointers.

Definition

A function pointer is a pointer to a function with a specific signature, it can only point to functions of the same signature.

Syntax

To declare a function pointer, use the following syntax:

RETURN_TYPE (*POINTER_NAME)(FUNCTION_ARGS)

A brief explanation:

The parenthesis around the pointer's name and the asterisk are necessary to differentiate from a function that takes the same arguments and returns a pointer. If it takes no argument, it's good convention to write void in the function arguments.

Example

#include <stdio.h>

int add(int a, int b){
 return a + b;
}

int mult(int a, int b){
 return a * b;
}

int mod(int a, int b){
 return a % b;
}

int main(){

 int (*op)(int, int) = add;
 int x = 6, y = 5;
 printf("%d\n", op(x, y));
 op = mult;
 printf("%d\n", op(x, y));
 op = mod;
 printf("%d\n", op(x, y));
}

And the result would be:

11
30
1

Function Pointer Arrays

Now for some some painful syntax, obviously the code above is a inefficient if we had more than 3 operations.

Syntax

Use the following syntax to declare a function pointer array:

RETURN_TYPE (*ARRAY_NAME[ARRAY_SIZE])(FUNCTION_ARGS)

The syntax is definitely confusing for some, but the only syntactical difference are the square brackets.
You can access the functions via their index like you would in every other array, and then you will have a function pointer. You may pass it arguments like you would a normal function, or assign it to a variable.

Example

#include <stdio.h>

int add(int a, int b){
 return a + b;
}

int mult(int a, int b){
 return a * b;
}

int mod(int a, int b){
 return a % b;
}

int main(){

 int (*op)(int, int) = add;
 int x = 6, y = 5;
 for(int i = 0; i < ARRAY_LENGTH; i++){
  printf("%d\n", funcPtrArr[i](x, y));
 }
}

Summary

And that's it! Function pointers are a very fun and useful feature of C, especially when used in arrays and as members of structs.
All code files are provided below.

funcptrs1.c
funcptrs2.c

Contents