Asperger Asperger - 1 month ago 10
C Question

Storing a function call from one header inside another header

#include "alotMonster.h"
#include "troll.h"

// alotMonster has a function named createAlotMonster()
// troll has a function named createTroll()

int main (void) {
createAlotMonster(createTroll());
}

// The function createTroll() is then saved inside a variable within createAlotMonster for later use.


How exactly can something like this be achieved in c? So basically storing a function call from one header inside another header.

Answer

A "function call" is not an object in C, i.e. it's not something you can store. A call is an action, it happens when a function is called. It's not something that has a size, i.e. it can't be stored.

You might want a function pointer, which is a way of referencing functions for calling later.

If we were to invent some prototypes, let's say

int createTroll(const char *name, int strength);

then you can reference that function using a pointer like this:

int (*troll_function)(const char *, int) = createTroll;

so you would have createAlotMonster() take such a pointer:

vod createAlotMonster(int (*monster_function)(const char *, int));

Then you can call it almost like you showed:

createAlotMonster(createTroll);

Note that there are no () after createTroll, we're not calling the function just passing its address to createAlotMonster().

Also note that there is no "storing inside header", headers can't store data. They can't do anything, they are just source files with declarations. The code that implements createAlotMonster() must be adjusted in order to support taking a function pointer as an argument for this to work, you can't force it to do something it wasn't designed to do.