C - Pointing to functions

Overview

Function pointers store the address of a function, enabling callbacks and flexible APIs.

Learning Objectives

  • Declare and use function pointers.
  • Use typedef to simplify function pointer syntax.
  • Pass function pointers as callbacks (e.g., to qsort).

Prerequisites

Basics

#include <stdio.h>

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

int main(void) {
  int (*op)(int,int) = &add;   // function pointer
  printf("%d\n", op(2,3));     // 5
}

Using typedef

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

int main(void) {
  binop op = add;              // & is optional
  printf("%d\n", op(2,3));
}

Callback example with qsort

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

int cmp_int(const void *a, const void *b) {
  int ia = *(const int*)a, ib = *(const int*)b;
  return (ia > ib) - (ia < ib);
}

int main(void) {
  int v[] = {4,1,3,2};
  size_t n = sizeof v / sizeof v[0];
  qsort(v, n, sizeof v[0], cmp_int);
  for (size_t i = 0; i < n; i++) printf("%d ", v[i]);
  printf("\n");
}

Common Pitfalls

  • Mismatch between function signature and pointer type.
  • Forgetting const-correctness in comparator callbacks.

Checks for Understanding

  1. How do you declare a pointer to a function int f(double)?
Show answer
int (*pf)(double);

Expected Output

  • Basics: 5
  • typedef: 5
  • qsort: 1 2 3 4

Practical Example: Dispatch Table

#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; }

typedef int (*op)(int,int);

int main(void){
  op ops[3] = { add, sub, mul };
  printf("%d %d %d\n", ops[0](7,3), ops[1](7,3), ops[2](7,3));
}

Expected Output: 10 4 21

Exercises

  1. Define a comparator for qsort that sorts integers in descending order.
  2. Build a small calculator using a table of function pointers keyed by an operator char.