How do function pointers work in C?

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.