Function Pointers and Callback Functions

9/1/2025

In C, a function pointer is a pointer that stores the address of the function.
Syntax: <return type> (*<pointer name>)(<parameter types>)
Example: int (*computeArea)(int, int);

To initalize a function pointer, we can assign the pointer with the address of the function:


typedef struct entityTag {
    int hp;
    int speed;
    int def;
    int (*isAlive)(struct entityTag);
    void (*takeDamage)(struct entityTag*, int);
} Entity;

int isAlive(Entity entity) {
    return entity.hp > 0;
}

void takeDamage(Entity* entity, int damage) {
    entity->hp -= damage;
}

Entity newEntity(int hp, int def, int speed) {
    //another way of declaring a struct variable
    Entity temp = {hp, def, speed, isAlive, takeDamage};
    return temp;
}

int main() {
    Entity entity = newEntity(10, 6, 3);
    printf("isAlive: %d\n", entity.isAlive(entity));
    entity.takeDamage(&entity, 10);
    printf("isAlive: %d\n", entity.isAlive(entity));

    return 0;
}

By layering structs and having function pointers as some of their components, we can replicate some concepts of the OOP paradigm in C:


typedef struct entityStructTag {
    int hp;
    int speed;
    int def;
    int (*isAlive)(struct entityStructTag);
    void (*takeDamage)(struct entityStructTag*, int);
} Entity;

typedef struct roaringKnightTag {
    Entity super; // the "object" RoaringKnight extends to Entity
    int (*checkPhase)(struct roaringKnightTag);
} RoaringKnight;

If a function can have a pointer variable to it, then it can also be passed to a function. This is called a callback function. The parameter to pass a function pointer follows the same concept as declaring a function pointer, except a parameter name will be used.


int pkStarstorm(int damage) {
    return 50 * damage;
}

int pkFlash(int damage) {
    int random = rand();
    if (random > 50)
        return 100 * damage;
    else
        return 0;
}

int pkBeam(int damage) {
    int min = 1;
    int max = 50;
    int random = (rand() % (max - min + 1)) + min;

    return 2000 + damage * random;
}

int attack(int (*callback)(int), int damage) {
    return callback(damage);
}

int main() {
    printf("pkStarstorm = %d\n", attack(pkStarstorm, 50));
    printf("pkFlash = %d\n", attack(pkFlash, 50));
    printf("pkBeam = %d\n", attack(pkBeam, 50));
	
    return 0;
}

In conclusion, a function pointer is a pointer that stores the address of the function specified while a callback function is a function pointer passed into a function that will use it to allow the parent function to have different behaviors without changing its core algorithm.

References:

  • https://www.geeksforgeeks.org/c/function-pointer-in-c/
  • https://levelup.gitconnected.com/uml-in-c-language-class-diagrams-6ed11aa34d9b
  • https://www.geeksforgeeks.org/c/callbacks-in-c/