</>EmbeddedInterview

What is a function pointer and where is it used?

MediumC Programming

Short answer: A function pointer holds the address of a function so the function can be called indirectly, chosen at run time. Embedded code uses them for interrupt vector tables, driver callbacks, state machines, command tables and "operations" structures that give C a form of polymorphism.

#include <stdint.h>
#include <stddef.h>

typedef void (*event_cb_t)(uint8_t event, void *ctx);

static event_cb_t user_cb;
static void *user_ctx;

void button_register(event_cb_t cb, void *ctx) { user_cb = cb; user_ctx = ctx; }

void button_isr(void)
{
    if (user_cb != NULL)          /* always check before calling */
        user_cb(1, user_ctx);
}

Common embedded uses

  • Vector table: an array of function pointers placed at the start of flash; the CPU reads the handler address from it on each interrupt.
__attribute__((section(".isr_vector")))
void (*const vector_table[])(void) = { (void (*)(void))&_estack, Reset_Handler, NMI_Handler, /* ... */ };
  • Callbacks: a driver calls application code when data arrives, without depending on the application.
  • State machines: a table indexed by state (and event) that gives the handler to run.
  • Driver operations structures: struct sensor_ops { int (*init)(void); int (*read)(int16_t *v); };, which lets the same code drive different sensors (like Linux's struct file_operations).
  • Command parsers: a table of { "name", handler } pairs.

Syntax help

int (*fp)(int, int);          /* pointer to function taking two ints, returning int */
int *fp2(int, int);           /* a function returning int* — not a pointer! */
int (*ops[4])(int, int);      /* array of 4 function pointers */

Use a typedef to keep declarations readable.

Safety and performance notes

  • Calling a NULL or corrupted function pointer jumps to a random address; on a Cortex-M this typically ends in a HardFault (or executes the vector table as code if the pointer is 0). Check for NULL and consider placing tables in flash (const) so they cannot be corrupted at run time.
  • Indirect calls prevent inlining and can be slightly slower.
  • The void *ctx parameter lets one callback serve several instances (C's version of a "this" pointer).