How do function pointers work in C?

I’ve been exploring C function pointer usage and wanted to understand how they work at a basic level. I’m looking for a clear explanation or examples showing how to declare, assign, and use function pointers in C for quick reference.

Sometimes I need multiple functions accessible dynamically, like a menu or command dispatcher:


#include <stdio.h>

void hello() { printf("Hello\n"); }
void bye()   { printf("Goodbye\n"); }

int main() {
    // Array of function pointers
    void (*funcArr[2])() = { hello, bye };

    funcArr[0]();  // Output: Hello
    funcArr[1]();  // Output: Goodbye

    return 0;
}

This is super handy for jump tables or mapping choices to actions.

I use this in embedded C projects all the time.

I often use function pointers for callbacks. Here’s how it works with parameters:

#include <stdio.h>

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

int main() {
    // Pointer to a function taking two ints and returning int
    int (*operation)(int, int);

    operation = add;
    int result = operation(5, 3);  // Calls add(5, 3)
    printf("Result: %d\n", result);  // Output: Result: 8

    return 0;
}

The syntax can look a bit tricky, but basically int (*operation)(int, int) means a pointer to a function that takes two ints and returns an int.

I use this pattern for callbacks in sorting, event handling, or modular code

Hey! I’ve worked with function pointers a lot :sweat_smile:. Think of them as variables that can store the address of a function, so you can call functions dynamically.

Example:


#include <stdio.h>

// Simple function
void greet() {
    printf("Hello, world!\n");
}

int main() {
    // Declare a function pointer
    void (*funcPtr)();

    // Assign the function to the pointer
    funcPtr = &greet;

    // Call the function via pointer
    funcPtr();  // Output: Hello, world!
    
    return 0;
}

void (*funcPtr)() declares a pointer to a function returning void and taking no arguments.

Using &greet is optional; funcPtr = greet; works too.