Back to Blog

C in 100 Seconds: Function Pointers | Episode 27

Daryl WongDaryl Wong

Video: C in 100 Seconds: Function Pointers — Callbacks and Dispatch | Episode 27 by Taught by Celeste AI - AI Coding Coach

Watch full page →

Function Pointers in C — Callbacks and Dispatch

C in 100 Seconds, Episode 27


A function pointer holds the address of a function. You can assign it, reassign it, call it, and pass it to other functions. This is how C achieves polymorphism — same variable, different behavior.

Declaring a Function Pointer

The syntax matches the function signature with an extra star and parentheses:

int (*fp)(int, int);

fp is a pointer to any function that takes two ints and returns an int.

Assign and Call

Point it at a function by name — no ampersand needed:

fp = add;
printf("add: %d\n", fp(10, 3));  // 13

fp = sub;
printf("sub: %d\n", fp(10, 3));  // 7

Same pointer, different function, different result.

Callbacks

Pass a function pointer as an argument — the receiving function calls it:

void apply(int (*op)(int, int), int x, int y) {
  printf("Result: %d\n", op(x, y));
}

apply(mul, 10, 3);  // Result: 30
apply(add, 5, 7);   // Result: 12

apply doesn't know which function it's running — it just calls whatever was passed in. That's a callback.

Why Function Pointers Matter

  • Callbacks — pass behavior as an argument (qsort, signal handlers)
  • Dispatch tables — arrays of function pointers for command routing
  • Strategy pattern — swap algorithms at runtime
  • Plugin systems — load and call functions dynamically

Full Code

#include <stdio.h>

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

void apply(int (*op)(int, int), int x, int y) {
  printf("Result: %d\n", op(x, y));
}

int main() {
  int (*fp)(int, int);

  fp = add;
  printf("add: %d\n", fp(10, 3));

  fp = sub;
  printf("sub: %d\n", fp(10, 3));

  apply(mul, 10, 3);
  apply(add, 5, 7);

  return 0;
}

Next episode: Arrays of Pointers — char star arrays, argv, and pointer tables.

Student code: github.com/GoCelesteAI/c-in-100-seconds/episode27