Pointer to function#

Until now, we used pointers that point to values. We can also point to functions.

Birthday collage analogy continued#

If we stay in the birthday collage analogy in Activity 41:

You have the collage in your room. You ask your friends to write the design instructions on a paper and they must assume that the collage has 5 columns. Each friend can describe, e.g., put my photo and message to the next free cell. Then you collect these recipes and execute them in your room.

Declaration & Usage#

#include <stdio.h>
int (*op)(int); // `op` is a function pointer that can point to a function that
                // returns an `int` and takes an `int` as argument.

int inc(int n) { return n + 1; }
int square(int n) { return n * n; }

int main(void) {
  int n = 4;

  op = inc;
  n = op(n);
  printf("%d\n", n);

  op = square;
  n = op(n);
  printf("%d\n", n);
}
5
25

Practical example#

To implement the map which applies a function on all elements of an array in problem Cryptography:

typedef char (*Func)(const char c, char shift);

static char *map(Func f, char *text, char shift) {
  for (size_t i = 0; text[i] != '\0'; ++i)
    text[i] = f(text[i], shift);
  return text;
}

char *caesar_encrypt(char *plaintext) {
  return map(caesar_encrypt_char, plaintext, CAESAR_SHIFT);
}

char *caesar_decrypt(char *plaintext) {
  return map(caesar_decrypt_char, plaintext, CAESAR_SHIFT);
}

Activity 47 (Applying arithmetic operations using an array of functions)

Start with the example above and create an array of function pointers called ops. Then iterate over the functions and apply the operations one after another on the n.

Hint: You can declare and initialize an array like this:

int (*ops[])(int) = {inc, square, inc, inc}; // Array of SIZE functions