WeCodeAcademy

C Function Pointers

A function pointer stores the address of a function, so you can pass behaviour as an argument.

ExampleC
#include <stdio.h>
#include <stdlib.h>

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

int apply(int (*op)(int, int), int x, int y) {
  return op(x, y);
}

int compare(const void *a, const void *b) {
  return *(const int *)a - *(const int *)b;
}

int main(void) {
  printf("%d\n", apply(add, 3, 4));
  printf("%d\n", apply(mul, 3, 4));

  int nums[] = {5, 2, 9, 1};
  qsort(nums, 4, sizeof(int), compare);
  for (int i = 0; i < 4; i++) printf("%d ", nums[i]);
  printf("\n");
  return 0;
}
Output
7
12
1 2 5 9

qsort from the standard library sorts any array; you tell it how to compare two items by passing a function pointer.

Quick check

What does a function pointer let you do?

Finish the quick check (and any code exercise) to complete this lesson, or mark it done yourself.

Tip: use the left and right arrow keys to move between lessons.